تخطَّ إلى المحتوى

Astro Adapter API

هذا المحتوى غير متوفر بلغتك بعد.

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',
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: string | URL

Defines the entrypoint for on-demand rendering.

Learn more about building a server entrypoint.

Type: AstroAdapterFeatureMap

أُضيفت في: 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

أُضيفت في: astro@3.0.0

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

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',
serverEntrypoint: '@example/my-adapter/server.js',
args: {
assets: config.build.assets
}
});
},
},
};
}

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

أُضيفت في: 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',
serverEntrypoint: '@example/my-adapter/server.js',
client: {
internalFetchHeaders: () => {
const deployId = process.env.DEPLOY_ID;
return deployId ? { 'Your-Header-ID': deployId } : {};
},
},
});
},
},
};
}

Type: URLSearchParams

Define the query parameters to append to all asset URLs (e.g. images, stylesheets, scripts, etc.). 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',
serverEntrypoint: '@example/my-adapter/server.js',
client: {
assetQueryParams: process.env.DEPLOY_ID
? new URLSearchParams({ yourParam: process.env.DEPLOY_ID })
: undefined,
},
});
},
},
};
}

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',
serverEntrypoint: '@example/my-adapter/server.js',
exports: ['handler']
});
},
},
};
}

Type: string | URL

أُضيفت في: 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',
serverEntrypoint: '@example/my-adapter/server.js',
previewEntrypoint: '@example/my-adapter/preview.js',
});
},
},
};
}

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.

Type: (manifest: SSRManifest, options: any) => Record<string, any>

An exported function that takes an SSR manifest as its first argument and an object containing your adapter args as its second argument. This should provide the exports required by your host.

For example, some serverless hosts expect you to export an handler() function. With the adapter API, you achieve this by implementing createExports() in your server entrypoint:

my-adapter/server.js
import { App } from 'astro/app';
export function createExports(manifest) {
const app = new App(manifest);
const handler = (event, context) => {
// ...
};
return { handler };
}

And then in your integration, where you call setAdapter(), provide this name in exports:

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

You can access the args defined by your adapter through the second argument of createExports(). This can be useful when you need to access build-time configuration in your server entrypoint. For example, your server might need to identify where assets generated by Astro are located:

my-adapter/server.js
import { App } from 'astro/app';
export function createExports(manifest, args) {
const assetsPath = args.assets;
const handler = (event, context) => {
// ...
};
return { handler };
}

Type: (manifest: SSRManifest, options: any) => Record<string, any>

An exported function that takes an SSR manifest as its first argument and an object containing your adapter args as its second argument.

Some hosts expect you to start the server yourselves, for example, by listening to a port. For these types of hosts, the adapter API allows you to export a start function, which will be called when the bundle script is run.

my-adapter/server.js
import { App } from 'astro/app';
export function start(manifest) {
const app = new App(manifest);
addEventListener('fetch', event => {
// ...
});
}

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';
export function start(manifest) {
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

أُضيفت في: 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)

Provide a value for integrationRouteData if 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

أُضيفت في: 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

أُضيفت في: 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

أُضيفت في: 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>

أُضيفت في: 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[]>

أُضيفت في: 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

أُضيفت في: 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:

export function start(manifest) {
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

أُضيفت في: 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:

export function start(manifest) {
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 }

أُضيفت في: 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:

export function start(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,
);
});
}

Just like astro/app, this module is used for rendering pages that have been prebuilt through astro build. This allows you to create a NodeApp providing all the methods available from App and additional methods useful for Node environments.

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

import { NodeApp } from 'astro/app/node';
import http from 'http';
export function start(manifest) {
const nodeApp = new NodeApp(manifest);
addEventListener('fetch', event => {
event.respondWith(
nodeApp.render(event.request)
);
});
}

The following additional methods are provided:

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

أُضيفت في: astro@4.0.0

Extends app.render() to also accept Node.js IncomingMessage objects in addition to standard Request objects as the first argument. The second argument is an optional object allowing you to control the rendering.

const response = await nodeApp.render(request);

Type: (req: NodeRequest | Request, allowPrerenderedRoutes?: boolean) => RouteData | undefined

Extends app.match() to also accept Node.js IncomingMessage objects in addition to standard Request objects.

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

Type: NodeAppHeadersJson | undefined
Default: undefined

أُضيفت في: astro@5.11.0

An array containing the headers configuration. Each entry maps a pathname to a list of headers that should be applied for that route. This is useful for applying headers such as CSP directives to prerendered routes.

Type: (headers: NodeAppHeadersJson) => void

أُضيفت في: astro@5.11.0

Loads headers configuration into the NodeApp instance.

nodeApp.setHeadersMap([
{
pathname: "/blog",
headers: [
{ key: "Content-Security-Policy", value: "default-src 'self'" },
]
}
]);

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

أُضيفت في: astro@4.2.0

Converts a NodeJS IncomingMessage into a standard Request object. This static method 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 { NodeApp } from 'astro/app/node';
import { createServer } from 'node:http';
const server = createServer(async (req, res) => {
const request = NodeApp.createRequest(req);
const response = await app.render(request);
})

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

أُضيفت في: astro@4.2.0

Streams a web-standard Response into a NodeJS server response. This static method 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 { NodeApp } from 'astro/app/node';
import { createServer } from 'node:http';
const server = createServer(async (req, res) => {
const request = NodeApp.createRequest(req);
const response = await app.render(request);
await NodeApp.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',
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',
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

أُضيفت في: astro@4.3.0

Defines whether the adapter is able to support i18n domains.

Type: AdapterSupport

أُضيفت في: 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',
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 { App } from 'astro/app';
import { setGetEnv } from "astro/env/setup"
setGetEnv((key) => process.env[key])
export function createExports(manifest) {
const app = new App(manifest);
const handler = (event, context) => {
// ...
};
return { handler };
}

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

import type { SSRManifest } from 'astro';
import { App } from 'astro/app';
import { setGetEnv } from 'astro/env/setup';
import { createGetEnv } from '../utils/env.js';
type Env = {
[key: string]: unknown;
};
export function createExports(manifest: SSRManifest) {
const app = new App(manifest);
const fetch = async (request: Request, env: Env) => {
setGetEnv(createGetEnv(env));
const response = await app.render(request);
return response;
};
return { default: { fetch } };
}

Type: AdapterSupport

أُضيفت في: 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',
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',
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"

أُضيفت في: 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',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
buildOutput: 'static'
}
});
},
},
};
}

Type: boolean

أُضيفت في: astro@5.9.3

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',
serverEntrypoint: '@example/my-adapter/server.js',
adapterFeatures: {
experimentalStaticHeaders: 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

أُضيفت في: 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.

أُضيفت في: 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"

أُضيفت في: 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',
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',
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.

ساهم المجتمع راعي