Expo 服务器

用于 Expo Router 项目的服务器端 API 和运行时。

Server
Bundled version:
~1.0.5

expo-server 是用于 Expo Router 的服务器端 API 和运行时库。它提供了一些可在你的 Expo Router API 路由或其他服务器代码中使用的辅助工具,并包含用于运行 Expo Router 服务器导出的适配器。

安装

🌐 Installation

Terminal
npx expo install expo-server

要在你的项目中使用 expo-server,你需要将你的 Expo Router 项目配置为以 server 模式导出。请按照 Expo Router 的 API 路由指南中的说明操作:

🌐 To use expo-server in your project, you need to configure your Expo Router project to export in server mode. Follow the instructions from Expo Router's API Routes guide:

API 路由

了解如何使用 Expo Router 创建服务器端点。

用法

🌐 Usage

expo-server 的运行时 API 只能在服务器端代码中使用,并且可以让你访问服务器端的运行时环境。运行时 API 提供的函数可以在请求处理程序的异步上下文中调用,并且可以让你获取当前请求的信息或安排与传入请求并发运行的任务。

访问请求元数据

🌐 Accessing request metadata

import { origin, environment } from 'expo-server'; export async function GET() { return Response.json({ isProduction: environment() == null, isStaging: environment() === 'staging', origin: origin(), }); }

安排任务

🌐 Scheduling tasks

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 }); }

适配器

🌐 Adapters

expo-server 提供了适配器,用于在不同环境或不同云提供商的无服务器函数上运行 Expo Router 的服务器端导出。通常,每个运行时都需要其自己的适配器,以便与 expo-server 运行时配合使用。在将应用部署到这些提供商之前,熟悉 npx expo export 命令的基础知识会很有帮助。

适配器提供者
expo-server/adapter/bunBun
expo-server/adapter/expressExpress
expo-server/adapter/httpNode.js
expo-server/adapter/netlifyNetlify Functions
expo-server/adapter/vercelVercel Functions
expo-server/adapter/workerdCloudflare Workers

要学习如何在不同的第三方服务上托管 API 路由,请按照 Expo Router 的 API 路由指南中的说明操作:

🌐 To learn how to host API routes on different third-party services, follow the instructions from Expo Router's API Routes guide:

API 路由

学习如何在第三方服务上托管 API 路由。

按照惯例,所有适配器都会导出一个 createRequestHandler 函数,该函数接受一个参数对象。该对象包含一个 build 参数,必须设置为 npx expo export 创建的 dist/server 输出目录的相对路径。一些适配器可能还接受更多值来配置运行时 API。

🌐 By convention, all adapters export a createRequestHandler function that accepts a parameters object. This accepts a build parameter that must be set to the relative path to the dist/server output directory that npx expo export created. Some adapters may also accept more values to configure the runtime 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

StatusError

Server

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

body

Server
Type: string

status

Server
Type: number

Methods

deferTask(fn)

Server
ParameterTypeDescription
fn() => void | Promise<unknown>

A task function to execute after the request handler has finished.


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.

Returns:
void

environment()

Server

Returns 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.

Returns:
string | null

A request environment name, or null for production.

origin()

Server

Returns the current request's origin URL.

This typically returns the request's Origin header, which contains the request origin URL or defaults to null.

Returns:
string | null

A request origin

runTask(fn)

Server
ParameterTypeDescription
fn() => Promise<unknown>

A task function to execute. The request handler will be kept alive until this task finishes.


Runs 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.

Returns:
void

setResponseHeaders(updateHeaders)

Server
ParameterTypeDescription
updateHeadersHeaders | Record<string, string | string[]> | (headers: Headers) => void | Headers

A Headers object, a record of headers, or a function that receives Headers to be updated or can return a Headers object that will be merged into the response headers.


Sets 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.

Returns:
void

Interfaces

ImmutableRequest

Server

Extends: _ImmutableRequest

An immutable version of the Fetch API's Request as received by middleware functions. It cannot be mutated or modified, its headers are immutable, and you won't have access to the request body.

PropertyTypeDescription
methodstring

The method read-only property of the POST, etc.) A String indicating the method of the request.

MDN Reference

urlstring

The url read-only property of the Request interface contains the URL of the request.

MDN Reference

MiddlewareMatcher

Server

Middleware matcher settings that restricts the middleware to run conditionally.

PropertyTypeDescription
methods(optional)string[]

Set this to a list of HTTP methods to conditionally run middleware on. By default, middleware will match all HTTP methods.

Example

['POST', 'PUT', 'DELETE']

patterns(optional)(string | RegExp)[]

Set this to a list of path patterns to conditionally run middleware on. This may be exact paths, paths containing parameter or catch-all segments ('/posts/[postId]' or '/blog/[...slug]'), or regular expressions matching paths.

Example

['/api', '/posts/[id]', '/blog/[...slug]']

MiddlewareSettings

Server

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]'], }, };
PropertyTypeDescription
matcher(optional)MiddlewareMatcher

Matcher definition that restricts the middleware to run conditionally.

Types

MiddlewareFunction(request)

Server

Middleware function type. Middleware run for every request in your app, or on specified conditonally matched methods and path patterns, as per MiddlewareMatcher.

Example

import type { MiddlewareFunction } from 'expo-server'; const middleware: MiddlewareFunction = async (request) => { console.log(`Middleware executed for: ${request.url}`); }; export default middleware;
ParameterTypeDescription
requestImmutableRequest

An ImmutableRequest with read-only headers and no body access

Returns:

Promise<Response | void> | Response | void