Vercel Security Guide: Environment Variables and Edge Functions

TL;DR

Vercel handles SSL, DDoS protection, and infrastructure security for you. What's left is yours. Get environment variables right (the NEXT_PUBLIC_ prefix ships a value to the browser), put authentication on your API routes, and set security headers. Be careful with preview deployments: by default they share production's environment variables.

What Vercel Handles for You

Some of the work is done before you write a line:

  • SSL/HTTPS: All deployments get automatic SSL certificates
  • DDoS protection: Built-in protection against denial of service attacks
  • Edge network: Requests are handled at the edge, reducing attack surface
  • Isolated functions: Serverless functions run in isolated environments
  • Automatic updates: Infrastructure is maintained and patched by Vercel

Environment Variables: The Most Common Mistake

Environment variables are where most Vercel security issues start. It comes down to one naming convention:

Variable NameWhere It's AvailableSafe for Secrets?
DATABASE_URLServer-side onlyYes
NEXT_PUBLIC_API_URLBrowser + ServerNo (public)
STRIPE_SECRET_KEYServer-side onlyYes
NEXT_PUBLIC_STRIPE_KEYBrowser + ServerOnly publishable keys

Critical rule: Any variable starting with NEXT_PUBLIC_ is bundled into your frontend JavaScript and visible to anyone. Never put secrets in NEXT_PUBLIC_ variables.

Common Environment Variable Mistakes

WRONG: Secret with NEXT_PUBLIC prefix
# This exposes your database password to the browser!
NEXT_PUBLIC_DATABASE_URL=postgres://user:password@host/db

# This exposes your secret API key!
NEXT_PUBLIC_OPENAI_KEY=sk-abc123...
CORRECT: Keep secrets without NEXT_PUBLIC
# Server-side only (safe)
DATABASE_URL=postgres://user:password@host/db
OPENAI_API_KEY=sk-abc123...

# Public variables (only non-secrets)
NEXT_PUBLIC_APP_URL=https://myapp.com
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_...

Securing API Routes

On Vercel, a Next.js API route is a serverless function with a public URL. Anyone can call it, so it needs an auth check:

Unprotected API route (vulnerable)
// pages/api/users.js or app/api/users/route.js
export async function GET() {
  // BAD: Anyone can access this
  const users = await db.users.findMany();
  return Response.json(users);
}
Protected API route (secure)
// app/api/users/route.js
import { getServerSession } from 'next-auth';

export async function GET(request) {
  // Check authentication
  const session = await getServerSession();

  if (!session) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }

  // Check authorization (e.g., admin only)
  if (session.user.role !== 'admin') {
    return Response.json({ error: 'Forbidden' }, { status: 403 });
  }

  const users = await db.users.findMany();
  return Response.json(users);
}

Security Headers Configuration

Add security headers in your next.config.js or vercel.json:

next.config.js security headers
/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'X-Content-Type-Options',
            value: 'nosniff',
          },
          {
            key: 'X-Frame-Options',
            value: 'DENY',
          },
          {
            key: 'X-XSS-Protection',
            value: '1; mode=block',
          },
          {
            key: 'Referrer-Policy',
            value: 'strict-origin-when-cross-origin',
          },
          {
            key: 'Content-Security-Policy',
            value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';",
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

Preview Deployments Security

Vercel builds a preview deployment for every git branch and PR. That's useful, and it's easy to forget what those previews can reach:

  • Preview deployments share environment variables with production by default
  • Preview URLs are public (though not easily guessable)
  • Consider using different environment variables for preview vs production

Protecting Preview Deployments

Preview Deployment Security Options

Enable Vercel Authentication for previews (available on all plans)

Use different API keys for preview environment

Don't put sensitive test data in preview databases

Consider password protecting preview deployments

Serverless Function Security

Input Validation

Validate all input in API routes
import { z } from 'zod';

const UserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

export async function POST(request) {
  const body = await request.json();

  // Validate input
  const result = UserSchema.safeParse(body);
  if (!result.success) {
    return Response.json(
      { error: 'Invalid input', details: result.error.issues },
      { status: 400 }
    );
  }

  // Use validated data
  const { email, name } = result.data;
  // ... process request
}

Rate Limiting

Basic rate limiting with Vercel KV
import { kv } from '@vercel/kv';

export async function POST(request) {
  const ip = request.headers.get('x-forwarded-for') || 'unknown';
  const key = `ratelimit:${ip}`;

  // Get current count
  const count = await kv.incr(key);

  // Set expiry on first request
  if (count === 1) {
    await kv.expire(key, 60); // 60 second window
  }

  // Check limit
  if (count > 10) { // 10 requests per minute
    return Response.json(
      { error: 'Rate limit exceeded' },
      { status: 429 }
    );
  }

  // Process request...
}

Vercel Security Checklist

Before Going Live

No secrets in NEXT_PUBLIC_ variables

All API routes have authentication checks

Security headers configured

Input validation on all endpoints

Rate limiting on sensitive endpoints

Preview deployments are protected or use test data

Environment variables are scoped correctly

Logs don't contain sensitive data

CORS configured appropriately

Are my environment variables encrypted on Vercel?

Yes. Vercel encrypts environment variables at rest and in transit, and injects them into your functions at runtime. The exception is anything prefixed NEXT_PUBLIC_, which gets bundled into your JavaScript and sent to every browser.

Can someone access my serverless function code?

No. Users can't see your serverless function source. They can only send it HTTP requests, and the code itself stays on Vercel's infrastructure.

Should I worry about preview deployment URLs being discovered?

Preview URLs are random and hard to guess, but an unprotected one is still public. For anything sensitive, turn on Vercel Authentication (available on all plans) or use a password protection solution.

How do I rotate a compromised secret on Vercel?

Update the variable in the Vercel dashboard and redeploy. The new value takes effect with that deploy. Then do the step people skip: rotate the credential with the service that issued it (generate a new API key with your provider).

Deploying to Vercel?

Scan your project for exposed secrets and security issues.

Tool & Platform Guides

Vercel Security Guide: Environment Variables and Edge Functions