Astro provides a programmatic JavaScript API that allows you to run Astro commands from code. This is useful for building tools, integrations, or custom workflows.
The JavaScript API is experimental and may change in future releases.
Available Functions
The Astro JavaScript API exports the following functions:
build() Build your Astro project for production
dev() Start the Astro development server
preview() Preview your production build locally
sync() Generate TypeScript types for your project
Installation
Install Astro in your project:
Basic Usage
Import the functions you need from the astro package:
import { build , dev , preview , sync } from 'astro' ;
// Build your site
await build ({ root: './my-project' });
// Start dev server
const server = await dev ({ root: './my-project' });
// Preview production build
const previewServer = await preview ({ root: './my-project' });
// Sync types
await sync ({ root: './my-project' });
Configuration
All API functions accept an AstroInlineConfig object that allows you to configure Astro programmatically. This object supports all the same options as astro.config.mjs.
await build ({
root: './my-project' ,
logLevel: 'info' ,
site: 'https://example.com' ,
outDir: './custom-dist' ,
});
Common Options
These options are available for all API functions:
root
string
default: "process.cwd()"
The root directory of your Astro project. Can be an absolute path or relative to the current working directory.
logLevel
'debug' | 'info' | 'warn' | 'error' | 'silent'
default: "'info'"
The logging level for Astro’s output.
mode
string
default: "'production'"
The mode to run Astro in. This affects environment variable loading and other build-time behavior.
Your deployed site URL. Used for generating sitemaps and canonical URLs.
The base path where your site is deployed.
The directory where build output is written.
Force a clean build by clearing the content layer cache.
Use Cases
Use the JavaScript API to integrate Astro into your existing build pipeline:
import { build } from 'astro' ;
async function buildSite () {
try {
await build ({
root: './src' ,
logLevel: 'info' ,
});
console . log ( 'Build complete!' );
} catch ( error ) {
console . error ( 'Build failed:' , error );
process . exit ( 1 );
}
}
buildSite ();
Testing
Start a dev server for integration tests:
import { dev } from 'astro' ;
let server ;
before ( async () => {
server = await dev ({
root: './test-site' ,
logLevel: 'silent' ,
});
});
after ( async () => {
await server . stop ();
});
Custom Integrations
Build custom tooling that leverages Astro’s type generation:
import { sync } from 'astro' ;
await sync ({
root: './my-project' ,
logLevel: 'info' ,
});
console . log ( 'TypeScript types generated!' );
Next Steps
Explore the individual API function references for detailed parameter information and examples: