Pular para o conteúdo

Astro Adapter API

Este conteúdo não está disponível em sua língua ainda.

Astro is designed to make it easy to deploy to any cloud provider for on-demand rendering, also known as server-side rendering (SSR). This ability is provided by adapters, which are integrations. See the on-demand rendering guide to learn how to use an existing adapter.

An adapter is a special kind of integration that provides an entrypoint for server rendering at request time. An adapter has access to the full Integration API and does two things:

  • Implements host-specific APIs for handling requests.
  • Configures the build according to host conventions.

Create an integration and call the setAdapter() function in the astro:config:done hook. This allows you to define a server entrypoint and the features supported by your adapter.

The following example creates an adapter with a server entrypoint and stable support for Astro static output:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
staticOutput: 'stable'
}
});
},
},
};
}

The setAdapter() function accepts an object containing the following properties:

Type: string

Defines a unique name for your adapter. This will be used for logging.

Type: "explicit" | "auto"
Default: "explicit"

Adicionado em: astro@6.0.0 Beta

Specifies the method Astro will use to resolve the server entrypoint: "auto" (recommended) or "explicit" (default, but deprecated):

  • "auto" (recommended): You are responsible for providing a valid module as an entrypoint using either serverEntrypoint or, if you need further customization at the Vite level using vite.build.rollupOptions.input.
  • "explicit" (deprecated): You must provide the exports required by the host in the server entrypoint using a createExports() function before passing them to setAdapter() as an exports list. This supports adapters built using the Astro 5 version of the Adapter API. By default, all adapters will receive this value to allow backwards compatibility. However, no new adapters should be created with this value. Existing adapters should override this default value with "auto" as soon as they are able to migrate to the new v6 API.

The following example defines the entrypointResolution and serverEntrypoint to tell Astro that a custom entrypoint is provided:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/custom-entrypoint.js',
});
},
},
};
}

The following example defines the entrypointResolution and Rollup options to tell Astro that a custom entrypoint is provided:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
updateConfig({
vite: {
build: {
rollupOptions: {
input: '@example/my-adapter/custom-entrypoint.js'
}
}
}
})
},
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
});
},
},
};
}
Learn more about how to build a server entrypoint.

Type: string | URL

Defines the entrypoint for on-demand rendering.

Type: AstroAdapterFeatureMap

Adicionado em: astro@3.0.0

A map of Astro’s built-in features supported by the adapter. This allows Astro to determine which features an adapter supports, so appropriate error messages can be provided.

Discover the available Astro features that an adapter can configure.

Type: AstroAdapterFeatures

Adicionado em: astro@3.0.0

An object that specifies which adapter features that change the build output are supported by the adapter.

Type: { internalFetchHeaders?: Record<string, string> | () => Record<string, string>; assetQueryParams?: URLSearchParams; }

Adicionado em: astro@5.15.0

A configuration object for Astro’s client-side code.

Type: Record<string, string> | () => Record<string, string>

Defines the headers to inject into Astro’s internal fetch calls (e.g. Actions, View Transitions, Server Islands, Prefetch). This can be an object of headers or a function that returns headers.

The following example retrieves a DEPLOY_ID from the environment variables and, if provided, returns an object with the header name as key and the deploy id as value:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ config, setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
client: {
internalFetchHeaders: () => {
const deployId = process.env.DEPLOY_ID;
return deployId ? { 'Your-Header-ID': deployId } : {};
},
},
});
},
},
};
}

Type: URLSearchParams

Defines the query parameters to append to all asset URLs (e.g. images, stylesheets, scripts). This is useful for adapters that need to track deployment versions or other metadata.

The following example retrieves a DEPLOY_ID from the environment variables and, if provided, returns an object with a custom search parameter name as key and the deploy id as value:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ config, setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
client: {
assetQueryParams: process.env.DEPLOY_ID
? new URLSearchParams({ yourParam: process.env.DEPLOY_ID })
: undefined,
},
});
},
},
};
}

Type: string | URL

Adicionado em: astro@1.5.0

Defines the path or ID of a module in the adapter’s package that is responsible for starting up the built server when astro preview is run.

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ config, setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
previewEntrypoint: '@example/my-adapter/preview.js',
});
},
},
};
}

Type: any

A JSON-serializable value that will be passed to the adapter’s server entrypoint at runtime. This is useful to pass an object containing build-time configuration (e.g. paths, secrets) to your server runtime code.

The following example defines an args object with a property that identifies where assets generated by Astro are located:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ config, setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'explicit',
args: {
assets: config.build.assets
},
serverEntrypoint: '@example/my-adapter/server.js'
});
},
},
};
}

Type: string[]

Defines an array of named exports to use in conjunction with the createExports() function of your server entrypoint.

The following example assumes that createExports() provides an export named handler:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ config, setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'explicit',
exports: ['handler'],
serverEntrypoint: '@example/my-adapter/server.js'
});
},
},
};
}

Adicionado em: astro@6.0.0 Beta

Adapters can provide a custom prerenderer to control how pages are prerendered by using the setPrerenderer() function in the astro:build:start hook.

The following example shows how an adapter can set a custom prerenderer:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:build:start': ({ setPrerenderer }) => {
setPrerenderer((defaultPrerenderer) => ({
name: 'my-prerenderer',
async setup() {
// Start a preview server
},
async getStaticPaths() {
// Returns array of { pathname: string, route: RouteData }
return defaultPrerenderer.getStaticPaths();
},
async render(request, { routeData }) {
// request: Request, options: { routeData: RouteData }
// Custom rendering logic, e.g. make HTTP requests to a preview server
const response = await fetch(`http://localhost:4321${new URL(request.url).pathname}`);
return response;
},
async teardown() {
// Stop the preview server
}
}));
},
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
});
},
},
};
}

The factory function receives the default prerenderer, allowing you to wrap or extend its behavior. This is useful when you only need to customize specific aspects of prerendering.

You will need to create a file that executes during server-side requests to enable on-demand rendering with your particular host. Astro’s adapter API attempts to work with any type of host and gives a flexible way to conform to the host APIs.

This file should conform to what the host expects. For example, some serverless hosts expect you to export an handler() function:

my-adapter/server.js
import { createApp } from 'astro/app/entrypoint';
const app = createApp();
export async function handler(event, context) {
// ...
}

If you need to access build-time configuration in your server entrypoint, you can pass via a virtual module. For example, your server might need to identify where assets generated by Astro are located.

First, create and register a Vite plugin to serialize the data:

my-adapter.mjs
const VIRTUAL_MODULE_ID = 'virtual:@example/my-adapter:config';
const RESOLVED_VIRTUAL_MODULE_ID = '\0' + VIRTUAL_MODULE_ID;
function createConfigPlugin(config) {
return {
name: VIRTUAL_MODULE_ID,
resolveId: {
filter: {
id: new RegExp(`^${VIRTUAL_MODULE_ID}$`),
},
handler() {
return RESOLVED_VIRTUAL_MODULE_ID;
},
},
load: {
filter: {
id: new RegExp(`^${RESOLVED_VIRTUAL_MODULE_ID}$`),
},
handler() {
return `
export const assets = ${JSON.stringify(config.build.assets)};
`;
},
},
};
}
export default function createIntegration() {
let _config;
return {
name: '@example/my-adapter',
hooks: {
'astro:config:setup': ({ config, updateConfig }) => {
_config = config;
updateConfig({
vite: {
plugins: [createConfigPlugin(_config)]
}
})
},
'astro:config:done': ({ config, setAdapter }) => {
_config = config;
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
});
},
},
};
}

You can create internal types if needed:

virtual.d.ts
declare module 'virtual:@example/my-adapter:config' {
export const assets: string;
}

You can then import the virtual module:

my-adapter/server.js
import { createApp } from 'astro/app/entrypoint';
import { assets } from 'virtual:@example/my-adapter:config';
const app = createApp();
export async function handler(event, context) {
// ...
}

Adicionado em: astro@6.0.0 Beta

This module is used for rendering pages in development or that have been prebuilt through astro build. Astro uses the standard Request and Response objects. Hosts that have a different API for request/response should convert to these types in their adapter.

import { createApp } from 'astro/app/entrypoint';

Type: () => App

Returns an App instance.

This module is used for rendering pages that have been prebuilt through astro build. Astro uses the standard Request and Response objects. Hosts that have a different API for request/response should convert to these types in their adapter.

The App constructor accepts a required SSR manifest argument, and optionally an argument to enable or disable streaming, defaulting to true.

import { App } from 'astro/app';
import http from 'http';
const app = new App(manifest);
addEventListener('fetch', event => {
event.respondWith(
app.render(event.request)
);
});

The following methods are provided:

Type: (request: Request, options?: RenderOptions) => Promise<Response>

A method that accepts a required request argument and an optional RenderOptions object. This calls the Astro page that matches the request, renders it, and returns a promise to a Response object. This also works for API routes that do not render pages.

const response = await app.render(request);

Type: {addCookieHeader?: boolean; clientAddress?: string; locals?: object; prerenderedErrorPageFetch?: (url: ErrorPagePath) => Promise<Response>; routeData?: RouteData;}

An object that controls the rendering and contains the following properties:

Type: boolean
Default: false

Whether or not to automatically add all cookies written by Astro.cookie.set() to the response headers.

When set to true, they will be added to the Set-Cookie header of the response as comma-separated key-value pairs. You can use the standard response.headers.getSetCookie() API to read them individually. When set to false(default), the cookies will only be available from App.getSetCookieFromResponse(response).

const response = await app.render(request, { addCookieHeader: true });

Type: string
Default: request[Symbol.for("astro.clientAddress")]

The client IP address that will be made available as Astro.clientAddress in pages, and as ctx.clientAddress in API routes and middleware.

The example below reads the x-forwarded-for header and passes it as clientAddress. This value becomes available to the user as Astro.clientAddress.

const clientAddress = request.headers.get("x-forwarded-for");
const response = await app.render(request, { clientAddress });

Type: object

The context.locals object used to store and access information during the lifecycle of a request.

The example below reads a header named x-private-header, attempts to parse it as an object and pass it to locals, which can then be passed to any middleware function.

const privateHeader = request.headers.get("x-private-header");
let locals = {};
try {
if (privateHeader) {
locals = JSON.parse(privateHeader);
}
} finally {
const response = await app.render(request, { locals });
}

Type: (url: ErrorPagePath) => Promise<Response>
Default: fetch

Adicionado em: astro@5.6.0

A function that allows you to provide custom implementations for fetching prerendered error pages.

This is used to override the default fetch() behavior, for example, when fetch() is unavailable or when you cannot call the server from itself.

The following example reads 500.html and 404.html from disk instead of performing an HTTP call:

return app.render(request, {
prerenderedErrorPageFetch: async (url: string): Promise<Response> => {
if (url.includes("/500")) {
const content = await fs.promises.readFile("500.html", "utf-8");
return new Response(content, {
status: 500,
headers: { "Content-Type": "text/html" },
});
}
const content = await fs.promises.readFile("404.html", "utf-8");
return new Response(content, {
status: 404,
headers: { "Content-Type": "text/html" },
});
}
});

If not provided, Astro will fallback to its default behavior for fetching error pages.

Type: RouteData
Default: app.match(request)

Defines the information about a route. This is useful when you already know the route to render. Doing so will bypass the internal call to app.match() to determine the route to render.

const routeData = app.match(request);
if (routeData) {
return app.render(request, { routeData });
} else {
/* adapter-specific 404 response */
return new Response(..., { status: 404 });
}

Type: (request: Request, allowPrerenderedRoutes = false) => RouteData | undefined

Determines if a request is matched by the Astro app’s routing rules.

if(app.match(request)) {
const response = await app.render(request);
}

You can usually call app.render(request) without using .match because Astro handles 404s if you provide a 404.astro file. Use app.match(request) if you want to handle 404s in a different way.

By default, prerendered routes aren’t returned, even if they are matched. You can change this behavior by using true as the second argument.

Type: () => AstroIntegrationLogger

Adicionado em: astro@v3.0.0

Returns an instance of the Astro logger available to the adapter’s runtime environment.

const logger = app.getAdapterLogger();
try {
/* Some logic that can throw */
} catch {
logger.error("Your custom error message using Astro logger.");
}

Type: () => Partial<RemotePattern>[] | undefined

Adicionado em: astro@5.14.2

Returns a list of permitted host patterns for incoming requests when using on-demand rendering as defined in the user configuration.

Type: (pathname: string) => string

Adicionado em: astro@1.6.4

Removes the base from the given path. This is useful when you need to look up assets from the filesystem.

Type: (response: Response) => Generator<string, string[], any>

Adicionado em: astro@1.4.0

Returns a generator that yields individual cookie header values from a Response object. This is used to properly handle multiple cookies that may have been set during request processing.

The following example appends a Set-Cookie header for each header obtained from a response:

for (const setCookieHeader of app.setCookieHeaders(response)) {
response.headers.append('Set-Cookie', setCookieHeader);
}

Type: (response: Response) => Generator<string, string[]>

Adicionado em: astro@4.2.0

Returns a generator that yields individual cookie header values from a Response object. This works in the same way as app.setCookieHeaders(), but can be used at any time as it is a static method.

The following example appends a Set-Cookie header for each header obtained from a response:

for (const cookie of App.getSetCookieFromResponse(response)) {
response.headers.append('Set-Cookie', cookie);
}

Type: (forwardedHost: string, allowedDomains?: Partial<RemotePattern>[], protocol?: string = 'https') => boolean

Adicionado em: astro@5.14.2

Checks whether a forwardedHost matches any of the given allowedDomains. This static method accepts a third argument that allows you to override the host protocol, defaulting to https.

The following example retrieves the forwardedHost from the headers and checks if the host matches an allowed domain:

addEventListener('fetch', (event) => {
const forwardedHost = event.request.headers.get('X-Forwarded-Host');
if (App.validateForwardedHost(forwardedHost, manifest.allowedDomains)) {
/* do something */
}
});

Type: (hostname: string | undefined) => string | undefined

Adicionado em: astro@5.15.5

Validates a hostname by rejecting any name containing path separators. When a hostname is invalid, this static method will return undefined.

The following example retrieves the forwardedHost from the headers and sanitizes it:

addEventListener('fetch', (event) => {
const forwardedHost = event.request.headers.get('X-Forwarded-Host');
const sanitized = App.sanitizeHost(forwardedHost);
});

Type: (forwardedProtocol?: string, forwardedHost?: string, forwardedPort?: string, allowedDomains?: Partial<RemotePattern>[]) => { protocol?: string; host?: string; port?: string }

Adicionado em: astro@5.15.5

Validates the forwarded protocol, host, and port against the allowedDomains. This static method returns validated values or undefined for rejected headers.

The following example validates the forwarded headers against the authorized domains defined in the received manifest:

addEventListener('fetch', (event) => {
const validated = App.validateForwardedHeaders(
request.headers.get('X-Forwarded-Proto') ?? undefined,
request.headers.get('X-Forwarded-Host') ?? undefined,
request.headers.get('X-Forwarded-Port') ?? undefined,
manifest.allowedDomains,
);
});

This module is used in conjunction with astro/app to convert a NodeJS IncomingMessage into a web-standard Request and stream a web-standard Response into a NodeJS ServerResponse.

Type: (req: NodeRequest, options?: { skipBody?: boolean; allowedDomains?: Partial<RemotePattern>[]; }) => Request

Adicionado em: astro@6.0.0 Beta

Converts a NodeJS IncomingMessage into a standard Request object. This function accepts an optional object as the second argument, allowing you to define if the body should be ignored, defaulting to false, and the allowedDomains.

The following example creates a Request and passes it to app.render():

import { createRequest } from 'astro/app/node';
import { createServer } from 'node:http';
const server = createServer(async (req, res) => {
const request = createRequest(req);
const response = await app.render(request);
})

Type: (source: Response, destination: ServerResponse) => Promise<ServerResponse<IncomingMessage> | undefined>

Adicionado em: astro@6.0.0 Beta

Streams a web-standard Response into a NodeJS server response. This function takes a Response object and the initial ServerResponse before returning a promise of a ServerResponse object.

The following example creates a Request, passes it to app.render(), and writes the response:

import { createRequest, writeResponse } from 'astro/app/node';
import { createServer } from 'node:http';
const server = createServer(async (req, res) => {
const request = createRequest(req);
const response = await app.render(request);
await writeResponse(response, res);
})

Astro features are a way for an adapter to tell Astro whether they are able to support a feature, and also the adapter’s level of support.

When using these properties, Astro will:

  • run specific validation;
  • emit contextual information to the logs;

These operations are run based on the features supported or not supported, their level of support, the desired amount of logging, and the user’s own configuration.

The following configuration tells Astro that this adapter has experimental support for the Sharp-powered built-in image service:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
sharpImageService: 'experimental'
}
});
},
},
};
}

If the Sharp image service is used, Astro will log a warning and error to the terminal based on your adapter’s support:

[@example/my-adapter] The feature is experimental and subject to issues or changes.
[@example/my-adapter] The currently selected adapter `@example/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build.

A message can additionally be provided to give more context to the user:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
sharpImageService: {
support: 'limited',
message: 'This adapter has limited support for Sharp. Certain features may not work as expected.'
}
}
});
},
},
};
}

This object contains the following configurable features:

Type: AdapterSupport

Defines whether the adapter is able to serve static pages.

Type: AdapterSupport

Defines whether the adapter is able to serve sites that include a mix of static and on-demand rendered pages.

Type: AdapterSupport

Defines whether the adapter is able to serve on-demand rendered pages.

Type: AdapterSupport

Adicionado em: astro@4.3.0

Defines whether the adapter is able to support i18n domains.

Type: AdapterSupport

Adicionado em: astro@4.10.0

Defines whether the adapter is able to support getSecret() exported from astro:env/server. When enabled, this feature allows your adapter to retrieve secrets configured by users in env.schema.

The following example enables the feature by passing a valid AdapterSupportsKind value to the adapter:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
envGetSecret: 'stable'
}
});
},
},
};
}

The astro/env/setup module allows you to provide an implementation for getSecret(). In your server entrypoint, call setGetEnv() as soon as possible:

import { createApp } from 'astro/app/entrypoint';
import { setGetEnv } from "astro/env/setup"
setGetEnv((key) => process.env[key])
const app = createApp();
export async function handler(event, context) {
// ...
}

If the adapter supports secrets, be sure to call setGetEnv() before getSecret() when environment variables are tied to the request:

import { createApp } from 'astro/app/entrypoint';
import { setGetEnv } from 'astro/env/setup';
const app = createApp();
export default {
async fetch(request: Request, env: Record<string, unknown>) {
setGetEnv((key) => env[key]);
return await app.render(request);
}
}

Type: AdapterSupport

Adicionado em: astro@5.0.0

Defines whether the adapter supports image transformation using the built-in Sharp image service.

A set of features that changes the output of the emitted files. When an adapter opts in to these features, they will get additional information inside specific hooks and must implement the proper logic to handle the different output.

Type: boolean

Defines whether any on-demand rendering middleware code will be bundled when built.

When enabled, this prevents middleware code from being bundled and imported by all pages during the build:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
edgeMiddleware: true
}
});
},
},
};
}

Then, consume the hook astro:build:ssr, which will give you a middlewareEntryPoint, an URL to the physical file on the file system.

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
edgeMiddleware: true
}
});
},
'astro:build:ssr': ({ middlewareEntryPoint }) => {
// remember to check if this property exits, it will be `undefined` if the adapter doesn't opt in to the feature
if (middlewareEntryPoint) {
createEdgeMiddleware(middlewareEntryPoint)
}
}
},
};
}
function createEdgeMiddleware(middlewareEntryPoint) {
// emit a new physical file using your bundler
}

Type: "static" | "server"
Default: "server"

Adicionado em: astro@5.0.0

Allows you to force a specific output shape for the build. This can be useful for adapters that only work with a specific output type. For example, your adapter might expect a static website, but uses an adapter to create host-specific files. Defaults to server if not specified.

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
buildOutput: 'static'
}
});
},
},
};
}

Type: boolean

Adicionado em: astro@6.0.0 Beta

Whether or not the adapter provides experimental support for setting response headers for static pages. When this feature is enabled, Astro will return a map of the Headers emitted by the static pages. This map experimentalRouteToHeaders is available in the astro:build:generated hook for generating files such as a _headers that allows you to make changes to the default HTTP header.

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
staticHeaders: true,
},
});
},
'astro:build:generated': ({ experimentalRouteToHeaders }) => {
// use `experimentalRouteToHeaders` to generate a configuration file
// for your virtual host of choice
},
},
};
}

The value of the headers might change based on the features enabled/used by the application. For example, if CSP is enabled, the <meta http-equiv="content-security-policy"> element is not added to the static page. Instead, its content is available in the experimentalRouteToHeaders map.

Type: AdapterSupportsKind | AdapterSupportWithMessage

Adicionado em: astro@5.0.0

A union of valid formats to describe the support level for a feature.

Type: "deprecated" | "experimental" | "limited" | "stable" | "unsupported"

Defines the level of support for a feature by your adapter:

  • Use "deprecated" when your adapter deprecates support for a feature before removing it completely in a future version.
  • Use "experimental" when your adapter adds support for a feature, but issues or breaking changes are expected.
  • Use "limited" when your adapter only supports a subset of the full feature.
  • Use "stable" when the feature is fully supported by your adapter.
  • Use "unsupported" to warn users that they may encounter build issues in their project, as this feature is not supported by your adapter.

Adicionado em: astro@5.0.0

An object that allows you to define a support level for a feature and a message to be logged in the user console. This object contains the following properties:

Type: Exclude<AdapterSupportsKind, “stable”>

Defines the level of support for a feature by your adapter.

Type: string

Defines a custom message to log regarding the support of a feature by your adapter.

Type: "default" | "all"

Adicionado em: astro@5.9.0

An option to prevent showing some or all logged messages about an adapter’s support for a feature.

If Astro’s default log message is redundant, or confusing to the user in combination with your custom message, you can use suppress: "default" to suppress the default message and only log your message:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
sharpImageService: {
support: 'limited',
message: 'The adapter has limited support for Sharp. It will be used for images during build time, but will not work at runtime.',
suppress: 'default' // custom message is more detailed than the default
}
}
});
},
},
};
}

You can also use suppress: "all" to suppress all messages about support for the feature. This is useful when these messages are unhelpful to users in a specific context, such as when they have a configuration setting that means they are not using that feature. For example, you can choose to prevent logging any messages about Sharp support from your adapter:

my-adapter.mjs
export default function createIntegration() {
return {
name: '@example/my-adapter',
hooks: {
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: '@example/my-adapter',
entrypointResolution: 'auto',
serverEntrypoint: '@example/my-adapter/server.js',
supportedAstroFeatures: {
sharpImageService: {
support: 'limited',
message: 'This adapter has limited support for Sharp. Certain features may not work as expected.',
suppress: 'all'
}
}
});
},
},
};
}

The astro add command allows users to easily add integrations and adapters to their project. To allow your adapter to be installed with this command, add astro-adapter to the keywords field in your package.json:

{
"name": "example",
"keywords": ["astro-adapter"],
}

Once you publish your adapter to npm, running astro add example will install your package with any peer dependencies specified in your package.json and instruct users to update their project config manually.

Contribua Comunidade Sponsor