Node.js / TypeScript

Secure Your OpenAI API Key in Next.js

Next.js Route Handlers and Server Actions run on Node.js, but a single misconfigured NEXT_PUBLIC_ prefix or a leaked .env.local file exposes your sk-proj- key to the world. With KeyVault Edge the real key never sits in your app, and the token only works from your allowed hosts.

The Problem

This is what most Next.js codebases look like today. The OPENAI_API_KEY key (sk-proj-...) lives directly in the process environment. If your repo, your CI logs, or your deployment config leaks — so does your key.

TypeScript
// app/api/chat/route.ts  ← your real key leaves your server on every call
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY, // sk-proj-YOUR_REAL_KEY stored in .env.local
});

export async function POST(req: Request) {
  const { messages } = await req.json();

  const completion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages,
  });

  return Response.json(completion.choices[0].message);
}

The Fix

Send the request to the KeyVault Edge proxy at https://proxy.keyvaultedge.com with the provider's usual path, your kvt_ token in X-KV-Token and the provider's base URL in X-KV-Target. The proxy refuses requests whose Origin isn't on the token's allowed hosts, then injects your real OPENAI_API_KEY, so it never sits in your app's environment.

TypeScript
// app/api/chat/route.ts  ← real key never in this process; KVE_TOKEN is host-bound
export async function POST(req: Request) {
  const { messages } = await req.json();

  const response = await fetch("https://proxy.keyvaultedge.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-KV-Token": process.env.KVE_TOKEN!, // kvt_... token, server-side only
      "X-KV-Target": "https://api.openai.com",
      // Must match one of the token's allowed hosts
      Origin: process.env.APP_ORIGIN!,
    },
    body: JSON.stringify({
      model: "gpt-4o",
      messages,
    }),
  });

  const data = await response.json();
  return Response.json(data.choices[0].message);
}

Setup in 4 steps

1

Create a sanitized token at keyvaultedge.com

Sign in at keyvaultedge.com/login, go to Tokens → New Token, paste your OpenAI key (sk-proj-...), set provider to "OpenAI", and add your deployment domain (e.g. myapp.vercel.app). Copy the KVE_TOKEN that appears — this is the only credential your server needs.

2

Add KVE_TOKEN to your Next.js environment

In your .env.local (local) and Vercel dashboard (production), set KVE_TOKEN. Remove OPENAI_API_KEY entirely — your real key now lives only inside KeyVault Edge's encrypted store.

Shell
# .env.local
KVE_TOKEN=kvt_...your_token
APP_ORIGIN=https://yourdomain.com  # one of the token's allowed hosts

# Vercel CLI (production)
vercel env add KVE_TOKEN production
3

Replace the OpenAI SDK call with the KVE proxy

Point the request at https://proxy.keyvaultedge.com with the provider's usual path (e.g. /v1/chat/completions), send your token in X-KV-Token, the provider's base URL (https://api.openai.com) in X-KV-Target, and an Origin header matching one of the token's allowed hosts. The body is the provider's normal request body; the proxy sets the provider's auth header with your real key and forwards it.

4

Lock down domain binding and set rate limits

Back in the KeyVault Edge dashboard, under your token's settings, confirm the allowed hosts list matches your Vercel deployment URLs. Set a per-minute rate limit to cap runaway costs if your endpoint is ever abused.

What this protects, and what it doesn't

  • Your real OPENAI_API_KEY stays at the edge, so it can't leak from your repo, logs, bundle or server environment.
  • The kvt_ token is still a credential. A copied token can be replayed by anyone who can send the right headers, including a fake Origin from a server. The protection is that each token has its own rate limits, monthly cost cap and endpoint scope, and you can revoke it in one click without rotating the provider key.
  • The cost cap is estimated from the usage the provider reports, so a request already in flight can overshoot it slightly.

More on layered defences in how to protect your OpenAI API key. Plans and limits are on the pricing page.

Start protecting your keys

Your OpenAI key is one leaked .env file away from being exploited. With KeyVault Edge the real key stays at the edge, and the token that replaces it is capped, scoped and revocable in one click.