Back to Vercel

Module: index

packages/functions/docs/modules/index.md

16.1.229.5 KB
Original Source

Module: index

Table of contents

Interfaces

Type Aliases

Functions

Type Aliases

AddCacheTagApi

Ƭ AddCacheTagApi: (tag: string | string[]) => Promise<void>

Type declaration

▸ (tag): Promise<void>

Vercel AddCacheTag API. A function that adds one or more tags to the cache content.

Parameters
NameTypeDescription
tagstring | string[]One or more tags to add to the cache content.
Returns

Promise<void>

A promise that resolves when the tag is added.

Defined in

packages/functions/src/addcachetag/types.ts:8

Functions

addCacheTag

addCacheTag(tag): Promise<void>

Parameters

NameType
tagstring | string[]

Returns

Promise<void>

Defined in

packages/functions/src/addcachetag/index.ts:3


attachDatabasePool

attachDatabasePool(dbPool): void

Call this function right after creating a database pool with the database pool object as argument. This ensures that the current function instance stays alive long enough for idle database connections to be removed from the pool.

Example

ts
const pgPool = new Pool({
  connectionString: process.env.DATABASE_URL,
});
attachDatabasePool(pgPool);

Parameters

NameTypeDescription
dbPoolDbPoolThe database pool object. The supported pool types are: - PostgreSQL (pg) - MySQL2 - MariaDB - MongoDB - Redis (ioredis) - Cassandra (cassandra-driver) - OTHER: This method uses duck-typing to detect the pool type. Respectively you can pass in any object with a compatible interface.

Returns

void

Defined in

packages/functions/src/db-connections/index.ts:225


dangerouslyDeleteBySrcImage

dangerouslyDeleteBySrcImage(src, options?): Promise<void>

Parameters

NameType
srcstring | string[]
options?DangerouslyDeleteOptions

Returns

Promise<void>

Defined in

packages/functions/src/purge/index.ts:28


dangerouslyDeleteByTag

dangerouslyDeleteByTag(tag, options?): Promise<void>

Parameters

NameType
tagstring | string[]
options?DangerouslyDeleteOptions

Returns

Promise<void>

Defined in

packages/functions/src/purge/index.ts:12


experimental_attachDatabasePool

experimental_attachDatabasePool(dbPool): void

Deprecated

Use attachDatabasePool instead.

Parameters

NameType
dbPoolDbPool

Returns

void

Defined in

packages/functions/src/db-connections/index.ts:225


geolocation

geolocation(request): Geo

Returns the location information for the incoming request.

Example

js
import { geolocation } from '@vercel/functions';

export function GET(request) {
  const details = geolocation(request);
  return Response.json(details);
}

Parameters

NameTypeDescription
requestRequestThe incoming request object which provides the geolocation data

Returns

Geo

The location information of the request, in this way:

json
{
 "city": "New York",
 "country": "US",
 "flag": "🇺🇸",
 "countryRegion": "NY",
 "region": "iad1",
 "latitude": "40.7128",
 "longitude": "-74.0060"
 "postalCode": "10001"
}

Defined in

packages/functions/src/headers.ts:180


getCache

getCache(cacheOptions?): RuntimeCache

Retrieves the Vercel Runtime Cache.

Keys are hashed to ensure they are unique and consistent. The hashing function can be overridden by providing a custom keyHashFunction in the cacheOptions parameter.

To specify a namespace for the cache keys, you can pass a namespace option in the cacheOptions parameter. If a namespace is provided, the cache keys will be prefixed with the namespace followed by a separator (default is $). The namespaceSeparator can also be customized using the namespaceSeparator option.

Throws

If no cache is available in the context and InMemoryCache cannot be created.

Parameters

NameTypeDescription
cacheOptions?CacheOptionsOptional configuration for the cache.

Returns

RuntimeCache

An instance of the Vercel Runtime Cache.

Defined in

packages/functions/src/cache/index.ts:33


getEnv

getEnv(env?): Object

Get System Environment Variables exposed by Vercel.

See

https://vercel.com/docs/projects/environment-variables/system-environment-variables#system-environment-variables

Parameters

NameTypeDefault value
envObjectprocess.env

Returns

Object

NameTypeDescription
CIundefined | stringAn indicator that the code is running in a Continuous Integration environment. Example ts "1"
VERCELundefined | stringAn indicator to show that System Environment Variables have been exposed to your project's Deployments. Example ts "1"
VERCEL_AUTOMATION_BYPASS_SECRETundefined | stringThe Protection Bypass for Automation value, if the secret has been generated in the project's Deployment Protection settings.
VERCEL_BRANCH_URLundefined | stringThe domain name of the generated Git branch URL. The value does not include the protocol scheme https://. Example ts "*-git-*.vercel.app"
VERCEL_DEPLOYMENT_IDundefined | stringThe unique identifier for the deployment, which can be used to implement Skew Protection. Example ts "dpl_7Gw5ZMBpQA8h9GF832KGp7nwbuh3"
VERCEL_ENVundefined | stringThe Environment that the app is deployed and running on. Example ts "production"
VERCEL_GIT_COMMIT_AUTHOR_LOGINundefined | stringThe username attached to the author of the commit that the project was deployed by. Example ts "johndoe"
VERCEL_GIT_COMMIT_AUTHOR_NAMEundefined | stringThe name attached to the author of the commit that the project was deployed by. Example ts "John Doe"
VERCEL_GIT_COMMIT_MESSAGEundefined | stringThe message attached to the commit the deployment was triggered by. Example ts "Update about page"
VERCEL_GIT_COMMIT_REFundefined | stringThe git branch of the commit the deployment was triggered by. Example ts "improve-about-page"
VERCEL_GIT_COMMIT_SHAundefined | stringThe git SHA of the commit the deployment was triggered by. Example ts "fa1eade47b73733d6312d5abfad33ce9e4068081"
VERCEL_GIT_PREVIOUS_SHAundefined | stringThe git SHA of the last successful deployment for the project and branch. NOTE: This Variable is only exposed when an Ignored Build Step is provided. Example ts "fa1eade47b73733d6312d5abfad33ce9e4068080"
VERCEL_GIT_PROVIDERundefined | stringThe Git Provider the deployment is triggered from. Example ts "github"
VERCEL_GIT_PULL_REQUEST_IDundefined | stringThe pull request id the deployment was triggered by. If a deployment is created on a branch before a pull request is made, this value will be an empty string. Example ts "23"
VERCEL_GIT_REPO_IDundefined | stringThe ID of the repository the deployment is triggered from. Example ts "117716146"
VERCEL_GIT_REPO_OWNERundefined | stringThe account that owns the repository the deployment is triggered from. Example ts "acme"
VERCEL_GIT_REPO_SLUGundefined | stringThe origin repository the deployment is triggered from. Example ts "my-site"
VERCEL_PROJECT_PRODUCTION_URLundefined | stringA production domain name of the project. This is useful to reliably generate links that point to production such as OG-image URLs. The value does not include the protocol scheme https://. Example ts "myproject.vercel.app"
VERCEL_REGIONundefined | stringThe ID of the Region where the app is running. Possible values: - arn1 (Stockholm, Sweden) - bom1 (Mumbai, India) - cdg1 (Paris, France) - cle1 (Cleveland, USA) - cpt1 (Cape Town, South Africa) - dub1 (Dublin, Ireland) - fra1 (Frankfurt, Germany) - gru1 (São Paulo, Brazil) - hkg1 (Hong Kong) - hnd1 (Tokyo, Japan) - iad1 (Washington, D.C., USA) - icn1 (Seoul, South Korea) - kix1 (Osaka, Japan) - lhr1 (London, United Kingdom) - pdx1 (Portland, USA) - sfo1 (San Francisco, USA) - sin1 (Singapore) - syd1 (Sydney, Australia) - dev1 (Development Region) Example ts "iad1"
VERCEL_SKEW_PROTECTION_ENABLEDundefined | stringWhen Skew Protection is enabled in Project Settings, this value is set to 1. Example ts "1"
VERCEL_URLundefined | stringThe domain name of the generated deployment URL. The value does not include the protocol scheme https://. NOTE: This Variable cannot be used in conjunction with Standard Deployment Protection. Example ts "*.vercel.app"

Defined in

packages/functions/src/get-env.ts:6


invalidateBySrcImage

invalidateBySrcImage(src): Promise<void>

Parameters

NameType
srcstring | string[]

Returns

Promise<void>

Defined in

packages/functions/src/purge/index.ts:23


invalidateByTag

invalidateByTag(tag): Promise<void>

Parameters

NameType
tagstring | string[]

Returns

Promise<void>

Defined in

packages/functions/src/purge/index.ts:4


ipAddress

ipAddress(input): string | undefined

Returns the IP address of the request from the headers.

Example

js
import { ipAddress } from '@vercel/functions';

export function GET(request) {
  const ip = ipAddress(request);
  return new Response(`Your IP is ${ip}`);
}

Parameters

NameTypeDescription
inputHeaders | RequestThe incoming request object or headers.

Returns

string | undefined

The IP address of the request.

Defined in

packages/functions/src/headers.ts:131


next

next(init?): Response

Returns a Response that instructs the system to continue processing the request.

Example

<caption>No-op middleware</caption>
ts
import { next } from '@vercel/edge';

export default function middleware(_req: Request) {
  return next();
}

Example

<caption>Add response headers to all requests</caption>
ts
import { next } from '@vercel/edge';

export default function middleware(_req: Request) {
  return next({
    headers: { 'x-from-middleware': 'true' },
  });
}

Parameters

NameTypeDescription
init?ExtraResponseInitAdditional options for the response

Returns

Response

Defined in

packages/functions/src/middleware.ts:145


rewrite

rewrite(destination, init?): Response

Returns a response that rewrites the request to a different URL.

Example

<caption>Rewrite all feature-flagged requests from `/:path*` to `/experimental/:path*`</caption>
ts
import { rewrite, next } from '@vercel/edge';

export default async function middleware(req: Request) {
  const flagged = await getFlag(req, 'isExperimental');
  if (flagged) {
    const url = new URL(req.url);
    url.pathname = `/experimental{url.pathname}`;
    return rewrite(url);
  }

  return next();
}

Example

<caption>JWT authentication for `/api/:path*` requests</caption>
ts
import { rewrite, next } from '@vercel/edge';

export default function middleware(req: Request) {
  const auth = checkJwt(req.headers.get('Authorization'));
  if (!checkJwt) {
    return rewrite(new URL('/api/error-unauthorized', req.url));
  }
  const url = new URL(req.url);
  url.searchParams.set('_userId', auth.userId);
  return rewrite(url);
}

export const config = { matcher: '/api/users/:path*' };

Parameters

NameTypeDescription
destinationstring | URLnew URL to rewrite the request to
init?ExtraResponseInitAdditional options for the response

Returns

Response

Defined in

packages/functions/src/middleware.ts:101


waitUntil

waitUntil(promise): undefined | void

Extends the lifetime of the request handler for the lifetime of the given Promise

See

https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil

Example

js
import { waitUntil } from '@vercel/functions';

export function GET(request) {
  waitUntil(fetch('https://vercel.com'));
  return new Response('OK');
}

Parameters

NameTypeDescription
promisePromise<unknown>The promise to wait for.

Returns

undefined | void

Defined in

packages/functions/src/wait-until.ts:19