This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo Server
Expo Router 项目的服务器端 API 和运行时。
expo-server 是一个用于 Expo Router 的服务器端 API 和运行时库。它提供了可在 Expo Router API 路由或其他服务器代码中使用的辅助函数,并包含用于运行 Expo Router 服务器导出的适配器。
安装
要在项目中使用 expo-server,需要将 Expo Router 项目配置为以 server 模式导出。请按照 Expo Router 的 API 路由指南中的说明操作:
了解如何使用 Expo Router 创建服务器端点。
用法
expo-server 的运行时 API 只能在服务器端代码中使用,并可让你访问服务器端运行时环境。运行时 API 会公开一些函数,这些函数可在请求处理程序的异步上下文中调用,用于获取当前请求的信息,或安排与传入请求并发运行的任务。
访问请求元数据
import { origin, environment } from 'expo-server'; export async function GET() { return Response.json({ isProduction: environment() == null, isStaging: environment() === 'staging', origin: origin(), }); }
安排任务
import { runTask, deferTask } from 'expo-server'; export async function GET() { runTask(async () => { console.log('will run immediately.'); }); deferTask(async () => { console.log('will run after the response resolved.'); }); return Response.json({ success: true }); }
适配器
expo-server 提供适配器,可在不同环境或不同云服务提供商的无服务器函数上运行 Expo Router 服务器端导出。通常,每种运行时都需要自己的适配器,才能与 expo-server 运行时配合使用。在部署到这些服务提供商之前,建议先了解 npx expo export 命令的基本用法。
要了解如何在不同第三方服务上托管 API 路由,请按照 Expo Router 的 API 路由指南中的说明操作:
了解如何在第三方服务上托管 API 路由。
按照约定,所有适配器都会导出一个接受参数对象的 createRequestHandler 函数。该对象接受一个 build 参数,其值必须设为 npx expo export 创建的 dist/server 输出目录的相对路径。某些适配器还可能接受更多值来配置运行时 API。
import path from 'node:path'; import { createRequestHandler } from 'expo-server/adapter/http'; const onRequest = createRequestHandler({ build: path.join(process.cwd(), 'dist/server'), environment: process.env.NODE_ENV, });
API
Classes
Type: Class extends Error
An error response representation which can be thrown anywhere in server-side code.
A StatusError can be thrown by a request handler and will be caught by the expo-server
runtime and replaced by a Response with the status and body that's been passed to
the StatusError.
Example
import { StatusError } from 'expo-server'; export function GET(request, { postId }) { if (!postId) { throw new StatusError(400, 'postId parameter is required'); } }
StatusError Properties
Methods
Creates a loader function for routes that need access to the incoming HTTP request. Server loaders run on every request during SSR. If called during SSG where no request is available, this throws an error.
LoaderFunction<T>See: Data loaders for more information.
Example
import { createServerLoader } from 'expo-server'; export const loader = createServerLoader(async (request, params) => { const authHeader = request.headers.get('Authorization'); return { authenticated: !!authHeader }; });
Creates a loader function for routes that only need route parameters to load data. The callback receives no request object, making it safe to use for both SSG and SSR.
LoaderFunction<T>See: Data loaders for more information.
Example
import { createStaticLoader } from 'expo-server'; export const loader = createStaticLoader(async (params) => { const post = await fetchPost(params.id); return { post }; });
Defers a task until after a response has been sent.
This only calls the task function once the request handler has finished resolving a Response
and keeps the request handler alive until the task is completed. This is useful to run non-critical
tasks after the request handler, for example to log analytics datapoints. If the request handler
rejects with an error, deferred tasks won't be executed.
voidReturns the request's environment, if the server runtime supports this.
In EAS Hosting, the returned environment name is the alias or deployment identifier, but the value may differ for other providers.
string | nullA request environment name, or null for production.
Returns the current request's URL.
This typically returns the request's URL, or on certain platforms,
the origin of the request. This does not use the Origin header
in development as it may contain an untrusted value.
string | nullA request origin
Returns an immutable copy of the current request's headers.
ImmutableHeadersRuns a task immediately and instructs the runtime to complete the task.
A request handler may be terminated as soon as the client has finished the full Response
and unhandled promise rejections may not be logged properly. To run tasks concurrently to
a request handler and keep the request alive until the task is completed, pass a task
function to runTask instead. The request handler will be kept alive until the task
completes.
voidSets headers on the Response the current request handler will return.
This only updates the headers once the request handler has finished and resolved a Response.
It will either receive a set of Headers or an equivalent object containing headers, which will
be merged into the response's headers once it's returned.
voidInterfaces
Extends: _ImmutableHeaders
An immutable version of the Fetch API's Headers object. It cannot be mutated or modified.
Extends: _ImmutableRequest
An immutable version of the Fetch API's Request object. It cannot be mutated or modified, its
headers are immutable, and you won't have access to the request body.
Middleware matcher settings that restricts the middleware to run conditionally.
Exported from a +middleware.ts file to configure the server-side middleware function.
Example
import type { MiddlewareSettings } from 'expo-server'; export const unstable_settings: MiddlewareSettings = { matcher: { methods: ['GET'], patterns: ['/api', '/admin/[...path]'], }, };
Types
Function type for route loaders. Loaders are executed on the server during SSR/SSG to fetch data required by a route.
During SSG (Static Site Generation), the request parameter will be undefined
as there is no HTTP request at build time.
See: Data loaders for more information.
Example
import type { LoaderFunction } from 'expo-server'; export const loader: LoaderFunction = async (request, params) => { const data = await fetchData(params.id); return { data }; };
Promise<T> | T
Type: MetadataValue[]
Middleware function type. Middleware run for every request in your app, or on
specified conditionally matched methods and path patterns, as per MiddlewareMatcher.
See: Server middleware for more information.
Example
import type { MiddlewareFunction } from 'expo-server'; const middleware: MiddlewareFunction = async (request) => { console.log(`Middleware executed for: ${request.url}`); }; export default middleware;