The Astro integration API lets you extend Astro with a plain object that has a name and a set of hooks, functions Astro calls at fixed points in the dev server and build lifecycle. Inside those hooks you can update the config, add Vite plugins, inject routes and scripts, register middleware, and read or write files after the build. Every official integration (sitemap, MDX, the adapters) is built this way, and a local integration can be a single file in your project.
This guide explains the lifecycle, walks through the hooks you will use most, and builds three small integrations you can adapt: a build report, an injected route, and a post-build file generator.
Key Takeaways
- An integration is
{ name, hooks }, usually returned from a function so it can take options. Type it withAstroIntegrationfromastro.astro:config:setupis where most work happens:updateConfig(),injectRoute(),injectScript(),addMiddleware(),addWatchFile().astro:config:donegives you the final config;astro:build:donegives you the outputdirand the list of builtpages.- Use the provided
loggerinstead ofconsole.logso messages are labeled and respect log levels.- Start local in
src/integrations/orintegrations/, then publish to npm with theastro-integrationkeyword.
How integrations fit into Astro
You add an integration to the integrations array in astro.config.mjs. Astro calls each integration’s hooks in order, at each stage of its lifecycle. The main hooks are:
| Hook | When it runs | Typical use |
|---|---|---|
astro:config:setup |
Before the config is resolved | Change config, add Vite plugins, inject routes, scripts, middleware, renderers |
astro:config:done |
After all integrations ran setup | Read the final config, set an adapter, inject types |
astro:routes:resolved |
When routes are known (and on change in dev) | Inspect every route |
astro:server:setup |
Dev server created | Add Vite dev server middleware |
astro:server:start / done |
Dev server starts or stops | Logging, cleanup |
astro:build:start |
Build begins | Timing, setup |
astro:build:setup |
Before Vite builds | Adjust the Vite build config |
astro:build:generated |
Static pages generated | Inspect output before adapter work |
astro:build:done |
Build finished | Read or write files in the output folder |
Most integrations use two or three of these. The official integrations directory is full of examples, and the Astro config docs show where integrations sits in a project.
The smallest integration
Create a file anywhere in your project, for example integrations/hello.ts:
// integrations/hello.ts
import type { AstroIntegration } from 'astro';
export default function hello(): AstroIntegration {
return {
name: 'hello',
hooks: {
'astro:config:setup': ({ command, logger }) => {
logger.info(`Running astro ${command}`);
},
'astro:build:done': ({ pages, logger }) => {
logger.info(`Built ${pages.length} pages`);
},
},
};
}
Register it:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import hello from './integrations/hello.ts';
export default defineConfig({
integrations: [hello()],
});
Run npm run build and you will see lines prefixed with [hello]. The logger passed to every hook labels output with your integration’s name and has info, warn, error and debug methods.
Returning the integration from a function is the convention because it lets users pass options: hello({ verbose: true }).
astro:config:setup: changing Astro
This hook receives the user’s config and a set of helpers. The ones you will reach for most:
updateConfig(partial): deep-merges changes into the config. Use it to add Vite plugins, set markdown options or add other integrations’ settings.injectRoute({ pattern, entrypoint, prerender }): adds a page or endpoint from your package, without the user creating a file insrc/pages/.injectScript(stage, code): adds JavaScript to every page. Stages are'head-inline','before-hydration','page'and'page-ssr'.addMiddleware({ entrypoint, order }): registers middleware before ('pre') or after ('post') the user’s own.addWatchFile(path): restarts the dev server when a file (such as your own config file) changes.addRenderer(),addClientDirective(),addDevToolbarApp(): for UI framework support, customclient:*directives and toolbar apps.commandandisRestart: whether this isdev,build,previeworsync.
Here is an integration that adds a Vite plugin and a global script, with an option:
// integrations/build-stamp.ts
import type { AstroIntegration } from 'astro';
interface Options {
label?: string;
}
export default function buildStamp({ label = 'build' }: Options = {}): AstroIntegration {
const stamp = new Date().toISOString();
return {
name: 'build-stamp',
hooks: {
'astro:config:setup': ({ updateConfig, injectScript }) => {
updateConfig({
vite: {
define: {
__BUILD_STAMP__: JSON.stringify(stamp),
},
},
});
injectScript('page', `console.debug(${JSON.stringify(`${label}: ${stamp}`)});`);
},
},
};
}
Any file can now read __BUILD_STAMP__, and every page logs the stamp in the browser console. Declare declare const __BUILD_STAMP__: string; in src/env.d.ts so TypeScript knows about it.
Injecting a route
Routes let an integration ship pages or endpoints. This one adds a /health.json endpoint that reports the build time:
// integrations/health/index.ts
import type { AstroIntegration } from 'astro';
export default function health(): AstroIntegration {
return {
name: 'health',
hooks: {
'astro:config:setup': ({ injectRoute }) => {
injectRoute({
pattern: '/health.json',
entrypoint: new URL('./route.ts', import.meta.url),
prerender: true,
});
},
},
};
}
// integrations/health/route.ts
import type { APIRoute } from 'astro';
export const GET: APIRoute = () =>
new Response(JSON.stringify({ ok: true, builtAt: new Date().toISOString() }), {
headers: { 'Content-Type': 'application/json' },
});
entrypoint can be a file URL (as here) or a package specifier such as 'my-integration/route.ts' once published. Entrypoints can be .astro pages too, which is how integrations like Starlight provide entire sites. Set prerender: true for static output, or false for a route rendered on demand (which needs an adapter).
astro:build:done: working with the output
After the build, this hook gives you dir (a URL to the output folder) and pages (each with a pathname). It is the right place to generate files from the finished site. This integration writes a plain-text list of every page URL:
// integrations/url-list.ts
import type { AstroIntegration } from 'astro';
import { writeFile } from 'node:fs/promises';
export default function urlList(): AstroIntegration {
let site: URL | undefined;
return {
name: 'url-list',
hooks: {
'astro:config:done': ({ config, logger }) => {
site = config.site ? new URL(config.site) : undefined;
if (!site) logger.warn('Set `site` in astro.config.mjs to write absolute URLs.');
},
'astro:build:done': async ({ dir, pages, logger }) => {
const urls = pages
.map((p) => '/' + p.pathname)
.map((path) => (site ? new URL(path, site).href : path))
.sort();
await writeFile(new URL('urls.txt', dir), urls.join('\n') + '\n');
logger.info(`Wrote ${urls.length} URLs to urls.txt`);
},
},
};
}
Two patterns are worth noticing. First, astro:config:done stores the final config in a closure variable so later hooks can use it. Second, file paths are built with new URL('file', dir), because dir is a URL, not a string path.
The same structure powers real integrations like sitemap generators, search indexers (Pagefind runs on the built HTML), and llms.txt generators.
Adding middleware from an integration
Integrations can ship request-time logic through middleware:
// integrations/powered-by/index.ts
import type { AstroIntegration } from 'astro';
export default function poweredBy(): AstroIntegration {
return {
name: 'powered-by',
hooks: {
'astro:config:setup': ({ addMiddleware }) => {
addMiddleware({
entrypoint: new URL('./middleware.ts', import.meta.url),
order: 'post',
});
},
},
};
}
// integrations/powered-by/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (_context, next) => {
const response = await next();
response.headers.set('X-Powered-By', 'Astro');
return response;
});
Middleware runs at build time for prerendered pages and on each request for on-demand pages. The middleware guide explains the difference.
Dev server hooks
astro:server:setup receives the Vite dev server, so you can add Connect-style middleware for development-only endpoints or mock APIs:
// inside hooks
'astro:server:setup': ({ server, logger }) => {
server.middlewares.use('/__dev/ping', (_req, res) => {
res.end('pong');
});
logger.info('Dev ping endpoint at /__dev/ping');
},
This never runs during astro build, which makes it safe for tooling you do not want in production.
Testing and debugging
- Run with
astro build --verbose(orastro dev --verbose) to seelogger.debug()output. - Astro 7.4 added
astro build --timings, which shows how long build stages take and helps spot a slowastro:build:donehook. - Keep hooks idempotent. In dev,
astro:config:setupruns again on every config restart; checkisRestartif you need to skip one-time work. - Validate options at the start of the integration function and throw a clear error early.
Publishing an integration
Once it works locally, publish it:
- Create a package with
astroas apeerDependency, so users bring their own Astro version. - Export the integration function as the default export from your package entry.
- Add
"keywords": ["astro-integration"]topackage.json. The Astro integrations directory picks up packages with that keyword. - Ship TypeScript types, and document options in the README.
- Users can then install and register it in one step with
npx astro add your-package.
{
"name": "astro-url-list",
"version": "1.0.0",
"type": "module",
"exports": { ".": "./dist/index.js" },
"keywords": ["astro-integration", "withastro"],
"peerDependencies": { "astro": "^7.0.0" }
}
When to write an integration
Write one when the same setup repeats across projects, or when a feature needs to hook into the build. Common examples are generating files from the finished site, sharing config between client sites, adding a route that several projects need, and wiring a CMS or analytics script into every page. If you are starting a site rather than a tool, a Komal theme gives you a finished Astro project that you can extend with your own integrations. For the full list of hook arguments, see the Integration API reference, and for adding existing integrations to a CMS-driven site, the headless CMS guide.
FAQ
What is an Astro integration?
An Astro integration is an object with a name and hooks that Astro calls during the dev server and build lifecycle. Integrations can change the config, add Vite plugins, inject routes, scripts and middleware, add UI framework renderers, and process the build output.
How do I create a local Astro integration?
Write a function that returns { name, hooks } in a file such as integrations/my-integration.ts, import it in astro.config.mjs, and add it to the integrations array. No package or build step is needed for local use.
Which hook should I use to write files after the build?
Use astro:build:done. It receives dir, a URL to the output folder, and pages, the list of built pathnames. Write files with new URL('filename', dir) as the destination.
Can an Astro integration add pages?
Yes. Call injectRoute() in astro:config:setup with a pattern such as /health.json and an entrypoint pointing at an .astro page or a TypeScript endpoint. Set prerender to control whether it is built statically or rendered on demand.
How do I publish an Astro integration to npm?
Create a package that default-exports the integration function, list astro as a peer dependency, and add the astro-integration keyword to package.json. After publishing, users can install and configure it with npx astro add followed by your package name.