How to build an Astro integration
By Flavio
Updated
Tagged: Astro
Build an Astro integration from scratch using hooks, configuration updates, injected routes and scripts, package metadata, and local testing.
An Astro integration is a package that hooks into Astro’s lifecycle to change or extend how a site builds and runs.
With an integration, you can:
- update Astro configuration
- inject routes
- add scripts to pages
- configure Vite plugins
- run code before or after a build
In this tutorial we’ll build astro-build-info. It adds:
- a virtual module with build information
- a
/build-info.jsonroute - a tiny console message in development
It’s small enough to read top to bottom in a few minutes, and it uses the same integration API as larger packages.
Create the integration package
Start by creating a directory for the package:
mkdir astro-build-info
cd astro-build-info
npm init -y
npm install --save-dev astro typescript
Next, add a package.json file with the package metadata and exports:
{
"name": "@your-scope/astro-build-info",
"version": "0.1.0",
"type": "module",
"exports": {
".": {
"types": "./index.d.ts",
"default": "./index.js"
}
},
"files": [
"index.js",
"index.d.ts",
"virtual.d.ts",
"build-info-route.js"
],
"keywords": [
"astro-integration"
],
"peerDependencies": {
"astro": "^7.0.0"
}
}
Swap your-scope for your npm username or organization, since the unscoped astro-build-info name is already taken on npm.
The astro-integration keyword is what lets Astro and package directories recognize your package as an integration. Astro itself is a peer dependency because the project installing your integration already brings its own copy of Astro.
Return an integration object
Create index.js and export the integration factory:
export default function buildInfoIntegration(options = {}) {
const route = options.route || '/build-info.json'
return {
name: '@your-scope/astro-build-info',
hooks: {
'astro:config:setup': ({ injectRoute, injectScript }) => {
injectRoute({
pattern: route,
entrypoint: new URL(
'./build-info-route.js',
import.meta.url
),
prerender: true,
})
injectScript(
'page',
`console.debug('[astro-build-info] page loaded')`
)
},
},
}
}
The default export is a factory function that takes user options and returns an object with a globally unique name and a hooks object.
Each hook name tells you when Astro calls it. astro:config:setup runs while Astro is resolving configuration, and it’s the main place to add routes, scripts, renderers, and Vite plugins.
Add the route
Now create build-info-route.js for the injected route:
const builtAt = new Date().toISOString()
export function GET() {
return new Response(
JSON.stringify({
builtAt,
commit: process.env.COMMIT_SHA || null,
}),
{
headers: {
'content-type': 'application/json',
},
}
)
}
Because the route is prerendered, Astro writes a static JSON file at build time. The timestamp gets created when the route module runs during that build, and COMMIT_SHA can come from your deployment platform.
Passing a URL relative to import.meta.url makes sure the entrypoint resolves inside your installed integration package instead of looking inside the user’s project.
Add a virtual module
A virtual module lets you expose data to project code without writing a real file to disk.
Add a small Vite plugin inside index.js to serve it:
function buildInfoPlugin() {
const publicId = 'virtual:astro-build-info'
const resolvedId = `\0${publicId}`
return {
name: 'astro-build-info:virtual',
resolveId(id) {
if (id === publicId) {
return resolvedId
}
},
load(id) {
if (id === resolvedId) {
return `
export const commit = ${JSON.stringify(
process.env.COMMIT_SHA || null
)}
`
}
},
}
}
Then accept updateConfig in the setup hook and register the plugin:
'astro:config:setup': ({
injectRoute,
injectScript,
updateConfig,
}) => {
updateConfig({
vite: {
plugins: [buildInfoPlugin()],
},
})
// injectRoute() and injectScript() stay here
}
Any project using your integration can now import from the virtual module:
---
import { commit } from 'virtual:astro-build-info'
---
<p>Build: {commit || 'local'}</p>
TypeScript won’t know about that virtual module on its own, so you’ll want to export declaration files alongside it. Start with virtual.d.ts:
declare module 'virtual:astro-build-info' {
export const commit: string | null
}
Then create index.d.ts to reference it:
/// <reference path="./virtual.d.ts" />
import type { AstroIntegration } from 'astro'
export type BuildInfoOptions = {
route?: string
}
export default function buildInfoIntegration(
options?: BuildInfoOptions
): AstroIntegration
Your package.json includes both declaration files and exposes index.d.ts through the types export condition. That reference makes the virtual module declaration available automatically when a consuming project loads the integration’s types.
Only inject development code in development
Right now, our console message ships on every page.
The setup hook receives the current command, so you can limit the injected script to development:
'astro:config:setup': ({
command,
injectRoute,
injectScript,
updateConfig,
}) => {
if (command === 'dev') {
injectScript(
'page',
`console.debug('[astro-build-info] page loaded')`
)
}
// ...
}
Astro supports four script stages: head-inline, before-hydration, page, and page-ssr. Pick the latest stage that still works for what you need, and don’t inject browser JavaScript at all if you can do the job at build time instead.
Log through Astro
Hooks also receive an integration logger you can use for status messages:
'astro:config:setup': ({ logger }) => {
logger.info('Build info enabled')
}
Use it instead of decorating console.log() yourself. Your messages will match the rest of Astro’s output and respect the user’s verbosity settings.
Try not to log on every page or module transform, either. An integration shouldn’t drown out the application build.
Test it in a real Astro project
To test the package locally, spin up a sibling Astro project:
npm create astro@latest integration-demo
cd integration-demo
npm install
npm install ../astro-build-info
Register the integration in astro.config.mjs:
import { defineConfig } from 'astro/config'
import buildInfo from '@your-scope/astro-build-info'
export default defineConfig({
integrations: [
buildInfo({
route: '/meta/build.json',
}),
],
})
Start the dev server:
npm run dev
Then check the injected route to confirm it works:
curl http://localhost:4321/meta/build.json
After that, run a production build and inspect dist/meta/build.json. Make sure you test both astro dev and astro build, because they run through different code paths. It’s easy for an integration to work fine in development and still break during static generation.
Make astro add work
Astro lets users install integrations in one command:
npx astro add @your-scope/astro-build-info
To make that smooth for people installing your package:
- publish a normal npm package
- include the
astro-integrationkeyword - export the integration factory as the default export
- document any required environment variables
- keep setup safe to run more than once
astro add installs the package and wires it into the user’s Astro config automatically. It can’t guess unusual manual steps, so aim for sensible defaults that work without extra setup.
Use later lifecycle hooks
Setup isn’t the only hook available. You can also tap into later lifecycle hooks to inspect the completed build:
'astro:build:done': ({ dir, pages, logger }) => {
logger.info(
`Built ${pages.length} pages into ${dir.pathname}`
)
}
That comes in handy when you need to generate a search index, upload build artifacts, or report build output. Stick to the data Astro passes into the hook instead of mutating internals or relying on undocumented build directories.
Integration design rules
A few habits will save you and your users trouble as an integration grows:
- pick a unique, stable name
- validate options early with clear errors
- stick to documented hooks
- keep the default setup small and predictable
- leave unrelated user configuration alone
- make sure your Vite changes work alongside other integrations
- support both development and production builds cleanly
- declare the Astro versions you support
Always call updateConfig() instead of mutating the config object directly. Astro merges integration updates in order. If order matters, document it, or even better, design the integration so normal ordering doesn’t change how it behaves.
Want me to talk about your product? You can sponsor this site.
Related posts about astro: