Interface APIContext<Props, APIParams>

The APIContext is the object made available to endpoints and middleware. It is a subset of the Astro global object available in pages.

Reference

interface APIContext<Props, APIParams> {
    clientAddress: string;
    cookies: AstroCookies;
    currentLocale: undefined | string;
    generator: string;
    getActionResult: (<TAccept, TInputSchema, TAction>(action) => undefined | Awaited<ReturnType<TAction["safe"]>>);
    locals: Locals;
    params: APIParams;
    preferredLocale: undefined | string;
    preferredLocaleList: undefined | string[];
    props: Props;
    redirect: ((path, status?) => Response);
    request: Request;
    rewrite: ((rewritePayload) => Promise<Response>);
    site: undefined | URL;
    url: URL;
}

Type Parameters

  • Props extends Record<string, any> = Record<string, any>
  • APIParams extends Record<string, string | undefined> = Record<string, string | undefined>

Hierarchy (view full)

Properties

clientAddress: string

The address (usually IP address) of the user.

Throws an error if used within a static site, or within a prerendered page.

cookies: AstroCookies

Utility for getting and setting the values of cookies.

currentLocale: undefined | string

The current locale computed from the URL of the request. It matches the locales in i18n.locales, and returns undefined otherwise.

generator: string

A human-readable string representing the Astro version used to create the project. For example, "Astro v1.1.1".

getActionResult: (<TAccept, TInputSchema, TAction>(action) => undefined | Awaited<ReturnType<TAction["safe"]>>)

Get action result on the server when using a form POST.

Type declaration

locals: Locals

An object that middlewares can use to store extra information related to the request.

It will be made available to pages as Astro.locals, and to endpoints as context.locals.

Example usage:

// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware((context, next) => {
context.locals.greeting = "Hello!";
return next();
});

Inside a .astro file: ```astro

// src/pages/index.astro const greeting = Astro.locals.greeting;

{greeting}

```

Reference

params: APIParams

Parameters matching the page’s dynamic route pattern. In static builds, this will be the params generated by getStaticPaths. In SSR builds, this can be any path segments matching the dynamic route pattern.

Example usage:

import type { APIContext } from "astro"

export function getStaticPaths() {
return [
{ params: { id: '0' }, props: { name: 'Sarah' } },
{ params: { id: '1' }, props: { name: 'Chris' } },
{ params: { id: '2' }, props: { name: 'Fuzzy' } },
];
}

export async function GET({ params }: APIContext) {
return new Response(`Hello user ${params.id}!`)
}

Reference

preferredLocale: undefined | string

Available only when i18n configured and in SSR.

It represents the preferred locale of the user. It's computed by checking the supported locales in i18n.locales and locales supported by the users's browser via the header Accept-Language

For example, given i18n.locales equals to ['fr', 'de'], and the Accept-Language value equals to en, de;q=0.2, fr;q=0.6, the Astro.preferredLanguage will be fr because en is not supported, its quality value is the highest.

preferredLocaleList: undefined | string[]

Available only when i18n configured and in SSR.

It represents the list of the preferred locales that are supported by the application. The list is sorted via quality value.

For example, given i18n.locales equals to ['fr', 'pt', 'de'], and the Accept-Language value equals to en, de;q=0.2, fr;q=0.6, the Astro.preferredLocaleList will be equal to ['fs', 'de'] because en isn't supported, and pt isn't part of the locales contained in the header.

When the Accept-Header is *, the original i18n.locales are returned. The value * means no preferences, so Astro returns all the supported locales.

props: Props

List of props passed from getStaticPaths. Only available to static builds.

Example usage:

import type { APIContext } from "astro"

export function getStaticPaths() {
return [
{ params: { id: '0' }, props: { name: 'Sarah' } },
{ params: { id: '1' }, props: { name: 'Chris' } },
{ params: { id: '2' }, props: { name: 'Fuzzy' } },
];
}

export function GET({ props }: APIContext): Response {
return new Response(`Hello ${props.name}!`);
}

Reference

redirect: ((path, status?) => Response)

Create a response that redirects to another page.

Example usage:

// src/pages/secret.ts
export function GET({ redirect }) {
return redirect('/login');
}

Reference

Type declaration

request: Request

Information about the current request. This is a standard Request object

rewrite: ((rewritePayload) => Promise<Response>)

It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted by the rerouted URL passed as argument.

Example

// src/pages/secret.ts
export function GET(ctx) {
return ctx.rewrite(new URL("../"), ctx.url);
}

Type declaration

site: undefined | URL

The site provided in the astro config, parsed as an instance of URL, without base. undefined if the site is not provided in the config.

url: URL

The url of the current request, parsed as an instance of URL.

Equivalent to:

new URL(context.request.url)