Movatterモバイル変換


[0]ホーム

URL:


Docs

@vercel/functions API Reference (Node.js)

Last updated October 23, 2025
  1. Install the@vercel/functions package:
pnpm i @vercel/functions
  1. Import the@vercel/functions package (non-Next.js frameworks or Next.js versions below 15.1):
api/hello.ts
import { waitUntil, attachDatabasePool }from'@vercel/functions';exportdefault {fetch(request:Request) {// ...  },};

ForOIDC methods, import@vercel/oidc

If you’re usingNext.js 15.1 or above, we recommend using the built-inafter() function fromnext/serverinstead ofwaitUntil().

after() allows you to schedule work that runsafter the response has been sent or the prerender has completed. This is especially useful to avoid blocking rendering for side effects such as logging, analytics, or other background tasks.

app/api/hello/route.ts
import { after }from'next/server';exportasyncfunctionGET(request:Request) {constcountry=request.headers.get('x-vercel-ip-country')||'unknown';// Returns a response immediatelyconstresponse=newResponse(`You're visiting from${country}`);// Schedule a side-effect after the response is sentafter(async ()=> {// For example, log or increment analytics in the backgroundawaitfetch(`https://my-analytics-service.example.com/log?country=${country}`,    );  });return response;}
  • after() doesnot block the response. The callback runs once rendering or the response is finished.
  • after() is not aDynamic API; calling it does not cause a route to become dynamic.
  • If you need to configure or extend the timeout for tasks, you can usemaxDuration in Next.js.
  • For more usage examples (including inServer Components,Server Actions, orMiddleware), seeafter() in the Next.js docs.

If you'renot using Next.js 15.1 or above (or you are using other frameworks), you can use the methods from@vercel/functions below.

Description: Extends the lifetime of the request handler for the lifetime of the given Promise. ThewaitUntil() method enqueues an asynchronous task to be performed during the lifecycle of the request. You can use it for anything that can be done after the response is sent, such as logging, sending analytics, or updating a cache, without blocking the response.waitUntil() is available in Node.js and in theEdge Runtime.

Promises passed towaitUntil() will have the same timeout as the function itself. If the function times out, the promises will be cancelled.

NameTypeDescription
promisePromiseThe promise to wait for.

If you're using Next.js 15.1 or above, useafter()fromnext/server instead. Otherwise, see below.

api/hello.ts
import { waitUntil }from'@vercel/functions';asyncfunctiongetBlog() {constres=awaitfetch('https://my-analytics-service.example.com/blog/1');returnres.json();}exportdefault {fetch(request:Request) {waitUntil(getBlog().then((json)=>console.log({ json })));returnnewResponse(`Hello from${request.url}, I'm a Vercel Function!`);  },};

Description: Gets theSystem Environment Variables exposed by Vercel.

api/example.ts
import { getEnv }from'@vercel/functions';exportdefault {fetch(request) {const {VERCEL_REGION }=getEnv();returnnewResponse(`Hello from${VERCEL_REGION}`);  },};

Description: Returns the location information for the incoming request, in the following way:

{"city":"New York","country":"US","flag":"🇺🇸","countryRegion":"NY","region":"iad1","latitude":"40.7128","longitude":"-74.0060","postalCode":"10001"}
NameTypeDescription
requestRequestThe incoming request object which provides the IP
api/example.ts
import { geolocation }from'@vercel/functions';exportdefault {fetch(request) {constdetails=geolocation(request);returnResponse.json(details);  },};

Description: Returns the IP address of the request from the headers.

NameTypeDescription
requestRequestThe incoming request object which provides the IP
api/example.ts
import { ipAddress }from'@vercel/functions';exportdefault {fetch(request) {constip=ipAddress(request);returnnewResponse(`Your ip is${ip}`);  },};

Description: Marks a cache tag as stale, causing cache entries associated with that tag to be revalidated in the background on the next request.

NameTypeDescription
tagstring orstring[]The cache tag (or multiple tags) to invalidate.
api/example.ts
import { invalidateByTag }from'@vercel/functions';exportdefault {asyncfetch(request) {awaitinvalidateByTag('my-tag-name');returnnewResponse('Success');  },};

Description: Marks a cache tag as deleted, causing cache entries associated with that tag to be revalidated in the foreground on the next request. Use this method with caution because one tag can be associated with many paths and deleting the cache can cause many concurrent requests to the origin leading tocache stampede problem. A good use case for deleting the cache is when the origin has also been deleted, for example it returns a404 or410 status code.

NameTypeDescription
tagstring orstring[]The cache tag (or multiple tags) to dangerously delete.
options{ revalidationDeadlineSeconds: number }The time in seconds before the delete deadline. If a request is made before the deadline, it will revalidate in the background. Otherwise it will be dangerously deleted and revalidate in the foreground.
api/example.ts
import { dangerouslyDeleteByTag }from'@vercel/functions';exportdefault {asyncfetch(request) {awaitdangerouslyDeleteByTag('my-tag-name', {      revalidationDeadlineSeconds:10,    });returnnewResponse('Success');  },};

Description: Returns aRuntimeCache object that allows you to interact with the Vercel Runtime Cache in any Vercel region. Use this for storing and retrieving data across function, routing middleware, and build execution within a Vercel region.

NameTypeDescription
keyHashFunction(key: string) => stringOptional custom hash function for generating keys.
namespaceStringOptional namespace to prefix cache keys.
namespaceSeparatorStringOptional separator string for the namespace.

RuntimeCache provides the following methods:

MethodDescriptionParameters
getRetrieves a value from the Vercel Runtime Cache.key: string: The cache key
setStores a value in the Vercel Runtime Cache with optionalttl and/ortags. Thename option allows a human-readable label to be associated with the cache entry for observability purposes.
  • key: string: The cache key
  • value: unknown: The value to store
  • options?: { name?: string; tags?: string[]; ttl?: number }
    Configuration object (not required)
deleteRemoves a value from the Vercel Runtime Cache by keykey: string: The cache key to delete
expireTagExpires all cache entries associated with one or more tagstag: string | string[]: Tag or array of tags to expire
api/example.ts
import { getCache }from'@vercel/functions';exportdefault {asyncfetch(request) {constcache=getCache();// Get a value from cacheconstvalue=awaitcache.get('somekey');if (value) {returnnewResponse(JSON.stringify(value));    }constres=awaitfetch('https://api.vercel.app/blog');constoriginValue=awaitres.json();// Set a value in cache with TTL and tagsawaitcache.set('somekey', originValue, {      ttl:3600,// 1 hour in seconds      tags: ['example-tag'],    });returnnewResponse(JSON.stringify(originValue));  },};

After assigning tags to your cached data, use theexpireTag method to invalidate all cache entries associated with that tag. This operation is propagated globally across all Vercel regions within 300ms.

app/actions.ts
'use server';import { getCache }from'@vercel/functions';exportdefaultasyncfunctionaction() {awaitgetCache().expireTag('blog');}

The Runtime Cache is isolated per Vercel project and deployment environment (preview andproduction). Cached data is persisted across deployments and can be invalidated either through time-based expiration or by callingexpireTag. However, TTL (time-to-live) and tag updates aren't reconciled between deployments. In those cases, we recommend either purging the runtime cache or modifying the cache key.

The Runtime Cache API does not have first class integration withIncremental Static Regeneration. This means that:

  • Runtime Cache entry tags will not apply to ISR pages, so you cannot use expireTag to invalidate both caches.
  • Runtime Cache entry TTLs will have no effect on the ISR revalidation time and
  • Next.js'srevalidatePath andrevalidateTagAPI does not invalidate the Runtime Cache.

The following Runtime Cache limits apply:

  • The maximum size of an item in the cache is 2 MB. Items larger than this will not be cached.
  • A cached item can have a maximum of 128 tags.
  • The maximum tag length is 256 bytes.

Usage of the Vercel Runtime Cache is charged, learn more about pricing in theregional pricing docs.

Call this function right after creating a database pool to ensure proper connectionmanagement inFluid Compute. This function ensures that idle pool clients areproperly released before functions suspend.

Supports PostgreSQL (pg), MySQL2, MariaDB, MongoDB, Redis (ioredis), Cassandra (cassandra-driver), and other compatible pool types.

NameTypeDescription
dbPoolDbPoolThe database pool object.
api/database.ts
import { Pool }from'pg';import { attachDatabasePool }from'@vercel/functions';constpool=newPool({  connectionString:process.env.DATABASE_URL,});attachDatabasePool(pool);exportdefault {asyncfetch() {constclient=awaitpool.connect();try {constresult=awaitclient.query('SELECT NOW()');returnResponse.json(result.rows[0]);    }finally {client.release();    }  },};

This function has moved from @vercel/functions/oidc to@vercel/oidc-aws-credentials-provider. It is now deprecated from@vercel/functions and will be removed in a future release.

Description: Obtains the Vercel OIDC token and creates an AWS credential provider function that gets AWS credentials by calling the STSAssumeRoleWithWebIdentity API.

NameTypeDescription
roleArnstringARN of the role that the caller is assuming.
clientConfigObjectCustom STS client configurations overriding the default ones.
clientPluginsArrayCustom STS client middleware plugin to modify the client default behavior.
roleAssumerWithWebIdentityFunctionA function that assumes a role with web identity and returns a promise fulfilled with credentials for the assumed role.
roleSessionNamestringAn identifier for the assumed role session.
providerIdstringThe fully qualified host component of the domain name of the identity provider.
policyArnsArrayARNs of the IAM managed policies that you want to use as managed session policies.
policystringAn IAM policy in JSON format that you want to use as an inline session policy.
durationSecondsnumberThe duration, in seconds, of the role session. Defaults to 3600 seconds.
api/example.ts
import*as s3from'@aws-sdk/client-s3';import { awsCredentialsProvider }from'@vercel/oidc-aws-credentials-provider';consts3Client=news3.S3Client({  credentials:awsCredentialsProvider({    roleArn:process.env.AWS_ROLE_ARN,  }),});

This function has moved from @vercel/functions/oidc to @vercel/oidc. It is nowdeprecated from @vercel/functions and will be removed in a future release.

Description: Returns the OIDC token from the request context or the environment variable. This function first checks if the OIDC token is available in the environment variableVERCEL_OIDC_TOKEN. If it is not found there, it retrieves the token from the request context headers.

api/example.ts
import { ClientAssertionCredential }from'@azure/identity';import { CosmosClient }from'@azure/cosmos';import { getVercelOidcToken }from'@vercel/oidc';constcredentialsProvider=newClientAssertionCredential(process.env.AZURE_TENANT_ID,process.env.AZURE_CLIENT_ID,  getVercelOidcToken,);constcosmosClient=newCosmosClient({  endpoint:process.env.COSMOS_DB_ENDPOINT,  aadCredentials: credentialsProvider,});exportconstGET= ()=> {constcontainer= cosmosClient.database(process.env.COSMOS_DB_NAME).container(process.env.COSMOS_DB_CONTAINER);constitems=awaitcontainer.items.query('SELECT * FROM f').fetchAll();returnResponse.json({ items:items.resources });};

Was this helpful?

supported.
On this page

[8]ページ先頭

©2009-2025 Movatter.jp