How-to
2 min read

Connect to your own API

Learn how to configure your own API to trust Vercel's OpenID Connect (OIDC) Identity Provider (IdP)
Table of Contents

Secure backend access with OIDC federation is available in Beta on all plans

To configure your own API to accept Vercel's OIDC tokens, you need to validate the tokens using Vercel's JSON Web Keys (JWTs), available at https://oidc.vercel.com/.well-known/jwks.

Install the following package:

pnpm
yarn
npm
pnpm i jose

In the code example below, you use the jose.jwtVerify function to verify the token. The issuer, audience, and subject are validated against the token's claims.

/api/custom-api/route.ts
import http from 'node:http';
import * as jose from 'jose';
 
const JWKS = jose.createRemoteJWKSet(
  new URL('https://oidc.vercel.com/.well-known/jwks'),
);
 
const server = http.createServer((req, res) => {
  const token = req.headers['authorization']?.split('Bearer ')[1];
 
  if (!token) {
    res.statusCode = 401;
    res.end('Unauthorized');
    return;
  }
 
  try {
    const { payload } = jose.jwtVerify(token, JWKS, {
      issuer: 'https://oidc.vercel.com',
      audience: 'https://vercel.com/[TEAM_SLUG]',
      subject:
        'owner:[TEAM_SLUG]:project:[PROJECT_NAME]:environment:[ENVIRONMENT]',
    });
 
    res.statusCode = 200;
    res.end('OK');
  } catch (error) {
    res.statusCode = 401;
    res.end('Unauthorized');
  }
});
 
server.listen(3000);

Make sure that you:

  • Replace [TEAM_SLUG] with your team identifier from the Vercel's team URL
  • Replace [PROJECT_NAME] with your project's name in your project's settings
  • Replace [ENVIRONMENT] with one of Vercel's environments, development, preview or production

Install the following package:

pnpm
yarn
npm
pnpm i @vercel/functions

In the code example below, the getVercelOidcToken function is used to retrieve the OIDC token from your Vercel environment. You can then use this token to authenticate the request to the external API.

/api/custom-api/route.ts
import { getVercelOidcToken } from '@vercel/functions/oidc';
 
export const GET = async () => {
  const result = await fetch('https://api.example.com', {
    headers: {
      Authorization: `Bearer ${await getVercelOidcToken()}`,
    },
  });
 
  return Response.json(await result.json());
};
Last updated on July 20, 2024