@astrojs/ node
This adapter allows Astro to deploy your on-demand rendered routes and features to Node targets, including server islands, actions, and sessions.
If you’re using Astro as a static site builder, you don’t need an adapter.
Why Astro Node.js
Section titled “Why Astro Node.js”Node.js is a JavaScript runtime for server-side code. @astrojs/node can be used either in standalone mode or as middleware for other http servers, such as Express.
Installation
Section titled “Installation”Astro includes an astro add command to automate the setup of official integrations. If you prefer, you can install integrations manually instead.
Add the Node adapter to enable on-demand rendering in your Astro project with the astro add command.
This will install @astrojs/node and make the appropriate changes to your astro.config.* file in one step.
npx astro add nodepnpm astro add nodeyarn astro add nodeNow, you can enable on-demand rendering per page, or set your build output configuration to output: 'server' to server-render all your pages by default.
Manual Install
Section titled “Manual Install”First, add the Node adapter to your project’s dependencies using your preferred package manager.
npm install @astrojs/nodepnpm add @astrojs/nodeyarn add @astrojs/nodeThen, add the adapter to your astro.config.* file:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone', }),});Configuration
Section titled “Configuration”@astrojs/node can be configured by passing options into the adapter function. The following options are available:
Type: 'middleware' | 'standalone'
Controls whether the adapter builds to middleware or standalone mode.
middlewaremode allows the built output to be used as middleware for another Node.js server, like Express.js or Fastify.standalonemode builds a server that automatically starts when the entry module is run. This allows you to more easily deploy your build to a host without needing additional code.
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'middleware', }),});staticHeaders
Section titled “staticHeaders”Type: boolean
Default: false
@astrojs/node@10.0.0
If enabled, the adapter will serve the headers of prerendered pages using the Response object when provided by Astro features, such as Content Security Policy.
For example, when Content Security Policy is enabled, staticHeaders can be used to add the CSP headers to the Response object instead of creating a <meta> element:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ security: { csp: true }, adapter: node({ mode: 'standalone', staticHeaders: true, })});experimentalDisableStreaming
Section titled “experimentalDisableStreaming”Type: boolean
Default: false
@astrojs/node@9.3.0
Disables Astro’s default HTML streaming for pages rendered on demand.
HTML streaming helps with performance and generally provides a better visitor experience. In most cases, disabling streaming is not recommended.
However, when you need to disable HTML streaming (e.g. your host only supports non-streamed HTML caching at the CDN level), you can opt out of the default behavior:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone', experimentalDisableStreaming: true, }),});bodySizeLimit
Section titled “bodySizeLimit”Type: number
Default: 1073741824 (1 GB)
@astrojs/node@10.0.0
Sets the maximum allowed request body size in bytes. When the body of an incoming request exceeds this limit, an error will be thrown when the body is consumed.
Set to Infinity or 0 to disable the limit entirely. This may be useful if you need to accept very large request bodies, such as for video uploads.
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone', bodySizeLimit: 5 * 1024 * 1024 * 1024, // 5 GB }),});First, performing a build. Depending on which mode selected (see above) follow the appropriate steps below:
Middleware
Section titled “Middleware”The middleware mode builds a server entrypoint that exports a handler() function. This allows you to integrate an Astro project into an existing Node.js server (e.g. Express, Fastify) to render your on-demand routes.
The handler forwards all other requests to your server. This means your server must send the files located in your configured client directory (e.g. prerendered pages or images). You must also handle requests that do not match any route, or call the handler without next() to render your custom 404 page.
The following example shows a server that serves the client files, and uses the handler as middleware for all other requests:
import express from 'express';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = express();// Use the same value as the `base` option in your Astro config.const base = '/';app.use(base, express.static('dist/client/'));app.use(ssrHandler);
app.listen(8080);import Fastify from 'fastify';import fastifyMiddie from '@fastify/middie';import fastifyStatic from '@fastify/static';import { fileURLToPath } from 'node:url';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = Fastify({ logger: true });
await app .register(fastifyStatic, { root: fileURLToPath(new URL('./dist/client', import.meta.url)), }) .register(fastifyMiddie);app.use(ssrHandler);
app.listen({ port: 8080 });handler()
Section titled “handler()”Type: (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void, locals?: object) => void | Promise<void>
A function that renders the route of your project matching the request, and writes the response. This takes the Node.js IncomingMessage and ServerResponse of the request as its first two arguments.
You can optionally provide a next() function as the third argument. This allows your server to handle requests that do not match any route in your Astro project. Without it, the handler renders your custom 404 page instead.
The optional fourth argument is an object available as Astro.locals or context.locals in your routes and Astro middleware.
The following example forwards next() and provides a locals object to the handler:
import express from 'express';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = express();app.use(express.static('dist/client/'));app.use((req, res, next) => { const locals = { title: 'New title', };
ssrHandler(req, res, next, locals);});
app.listen(8080);import Fastify from 'fastify';import fastifyMiddie from '@fastify/middie';import fastifyStatic from '@fastify/static';import { fileURLToPath } from 'node:url';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = Fastify({ logger: true });
await app .register(fastifyStatic, { root: fileURLToPath(new URL('./dist/client', import.meta.url)), }) .register(fastifyMiddie);app.use((req, res, next) => { const locals = { title: 'New title', };
ssrHandler(req, res, next, locals);});
app.listen({ port: 8080 });Standalone
Section titled “Standalone”In standalone mode a server starts when the server entrypoint is run. By default it is built to ./dist/server/entry.mjs. You can run it with:
node ./dist/server/entry.mjsFor standalone mode the server handles file serving in addition to the page and API routes.
Custom host and port
Section titled “Custom host and port”You can override the host and port the standalone server runs on by passing them as environment variables at runtime:
HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjsBy default the standalone server uses HTTP. This works well if you have a proxy server in front of it that does HTTPS. If you need the standalone server to run HTTPS itself you need to provide your SSL key and certificate.
You can pass the path to your key and certification via the environment variables SERVER_CERT_PATH and SERVER_KEY_PATH. This is how you might pass them in bash:
SERVER_KEY_PATH=./private/key.pem SERVER_CERT_PATH=./private/cert.pem node ./dist/server/entry.mjsAssets
Section titled “Assets”In standalone mode, assets in your dist/client/ folder are served via the standalone server. You might be deploying these assets to a CDN, in which case the server will never actually be serving them. But in some cases, such as intranet sites, it’s fine to serve static assets directly from the application server.
Assets in the dist/client/_astro/ folder are the ones that Astro has built. These assets are all named with a hash and therefore can be given long cache headers. Internally the adapter adds this header for these assets:
Cache-Control: public, max-age=31536000, immutableSessions
Section titled “Sessions”The Astro Sessions API allows you to easily store user data between requests. This can be used for things like user data and preferences, shopping carts, and authentication credentials. Unlike cookie storage, there are no size limits on the data, and it can be restored on different devices.
Astro uses the local filesystem for session storage when using the Node adapter. If you would prefer to use a different session storage driver, you can specify it in your Astro config. See the session configuration reference for more details.
If your project does not use sessions, you can set session: false in your Astro config. The adapter will not configure the filesystem session driver, and the session runtime will be excluded from your server bundle.
Environment variables
Section titled “Environment variables”When using the astro:env secrets or process.env at runtime, neither Astro nor the adapter loads environment variables for you.
Some hosts may expose the environment variables you configure through their dashboard during the build and at runtime. Check your host’s documentation for setting and using environment variables within the specific platform.
When self-hosting, you can load environment variables through CLI commands or configuration files as appropriate:
DB_HOST=... DB_PASSWORD=... node ./dist/server/entry.mjsnpx @dotenvx/dotenvx run -- node ./dist/server/entry.mjsFROM node:lts AS runtimeWORKDIR /app
COPY . .
RUN npm installRUN npm run build
ENV DB_HOST=...ENV DB_PASSWORD=...CMD node ./dist/server/entry.mjs