@vercel/functions API Reference
- Install the
@vercel/functions
package:
pnpm i @vercel/functions
- Import the
@vercel/functions
package (non-Next.js frameworks or Next.js versions below 13.4):
ForOIDC methods, import@vercel/functions/oidc
If you’re usingNext.js 13.4 or above, we recommend using the built-inafter()
function fromnext/server
instead 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.
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 use
maxDuration
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 13.4 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.
Name | Type | Description |
---|---|---|
promise | Promise | The promise to wait for. |
If you're using Next.js 13.4 or above, useafter()
fromnext/server
instead. Otherwise, see below.
import { waitUntil }from'@vercel/functions';asyncfunctiongetBlog() {constres=awaitfetch('https://my-analytics-service.example.com/blog/1');returnres.json();}exportfunctionGET(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.
import { getEnv }from'@vercel/functions';exportfunctionGET(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"}
Name | Type | Description |
---|---|---|
request | Request | The incoming request object which provides the IP |
import { geolocation }from'@vercel/functions';exportfunctionGET(request) {constdetails=geolocation(request);returnResponse.json(details);}
Description: Returns the IP address of the request from the headers.
Name | Type | Description |
---|---|---|
request | Request | The incoming request object which provides the IP |
import { ipAddress }from'@vercel/functions';exportfunctionGET(request) {constip=ipAddress(request)returnnewResponse('Your ip is' ${ip});}
To use OIDC methods, import the@vercel/functions/oidc
package:
import { awsCredentialsProvider }from'@vercel/functions/oidc'exportfunctionGET() {...}
Description: Obtains the Vercel OIDC token and creates an AWS credential provider function that gets AWS credentials by calling the STSAssumeRoleWithWebIdentity
API.
Name | Type | Description |
---|---|---|
roleArn | string | ARN of the role that the caller is assuming. |
clientConfig | Object | Custom STS client configurations overriding the default ones. |
clientPlugins | Array | Custom STS client middleware plugin to modify the client default behavior. |
roleAssumerWithWebIdentity | Function | A function that assumes a role with web identity and returns a promise fulfilled with credentials for the assumed role. |
roleSessionName | string | An identifier for the assumed role session. |
providerId | string | The fully qualified host component of the domain name of the identity provider. |
policyArns | Array | ARNs of the IAM managed policies that you want to use as managed session policies. |
policy | string | An IAM policy in JSON format that you want to use as an inline session policy. |
durationSeconds | number | The duration, in seconds, of the role session. Defaults to 3600 seconds. |
import*as s3from'@aws-sdk/client-s3';import { awsCredentialsProvider }from'@vercel/functions/oidc';consts3Client=news3.S3Client({ credentials:awsCredentialsProvider({ roleArn:process.env.AWS_ROLE_ARN, }),});
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.
import { ClientAssertionCredential }from'@azure/identity';import { CosmosClient }from'@azure/cosmos';import { getVercelOidcToken }from'@vercel/functions/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?