KeyEnvKeyEnv

Vercel Integration

Sync KeyEnv secrets to Vercel projects automatically.

Vercel Integration

This guide shows how to use KeyEnv secrets with Vercel deployments. You can either sync secrets directly to Vercel or pull them at build time.

Overview

KeyEnv offers two ways to integrate with Vercel:

MethodBest ForHow It Works
Native SyncProduction appsAuto-push secrets to Vercel environment variables
Build-Time PullFull controlPull secrets during Vercel build process

Native Vercel Sync

Automatically sync secrets from KeyEnv to your Vercel project. When you update a secret in KeyEnv, it's pushed to Vercel immediately.

How It Works

  1. Connect your Vercel account via OAuth
  2. Map KeyEnv environments to Vercel projects/environments
  3. Secrets sync automatically when changed
  4. Optionally trigger a redeploy on update

Setup

1. Connect Vercel Account

  1. Go to Settings > Integrations in your KeyEnv dashboard
  2. Click Connect Vercel
  3. Authorize KeyEnv to access your Vercel account
  4. Select the Vercel team (if applicable)
  1. In your KeyEnv project, go to Settings > Vercel Sync
  2. Select your Vercel project from the dropdown
  3. Map environments:
KeyEnv EnvironmentVercel Environment
productionProduction
stagingPreview
developmentDevelopment
  1. Click Enable Sync

3. Initial Sync

Click Sync Now to push all current secrets to Vercel. Future changes sync automatically.

Environment Mapping

KeyEnv environments map to Vercel's three environment types:

  • Production - Live deployment on your main domain
  • Preview - Branch/PR deployments
  • Development - Local development via vercel dev

You can map multiple KeyEnv environments to a single Vercel environment, or vice versa.

Auto-Redeploy

Enable Auto-Redeploy to trigger a new deployment when secrets change:

  1. Go to your KeyEnv project > Settings > Vercel Sync
  2. Toggle Redeploy on Change
  3. Select which Vercel environments to redeploy

Auto-redeploy uses Vercel's Deploy Hooks. A new production deployment is triggered within 30 seconds of a secret change.

Sync Status

View sync status in the KeyEnv dashboard:

  • Synced - All secrets match Vercel
  • Pending - Changes waiting to sync
  • Error - Sync failed (check logs)

Build-Time Injection

Pull secrets from KeyEnv during your Vercel build. This gives you full control over when secrets are fetched.

Prerequisites

  1. A KeyEnv project with secrets configured
  2. A service token with access to production environment

Setup

1. Create a Service Token

  1. Go to Project Settings > Service Tokens
  2. Click Create Token
  3. Name it "Vercel Production"
  4. Select the production environment
  5. Copy the token

2. Add Token to Vercel

  1. Go to your Vercel project settings
  2. Navigate to Environment Variables
  3. Add a new variable:
    • Name: KEYENV_TOKEN
    • Value: Your service token
    • Environments: Production (and Preview if needed)

3. Update Build Command

In your vercel.json, modify the build command:

{
  "buildCommand": "curl -fsSL https://keyenv.dev/install.sh | bash && export PATH=\"$HOME/.keyenv/bin:$PATH\" && keyenv pull -e production && npm run build"
}

Or in package.json:

{
  "scripts": {
    "vercel-build": "curl -fsSL https://keyenv.dev/install.sh | bash && export PATH=\"$HOME/.keyenv/bin:$PATH\" && keyenv pull -e production && npm run build"
  }
}

Environment-Specific Builds

Use different environments for preview and production deployments.

Using VERCEL_ENV

Vercel sets VERCEL_ENV to production, preview, or development automatically:

{
  "scripts": {
    "vercel-build": "curl -fsSL https://keyenv.dev/install.sh | bash && export PATH=\"$HOME/.keyenv/bin:$PATH\" && keyenv pull -e $VERCEL_ENV && npm run build"
  }
}

Using Separate Tokens

For stricter security, create separate service tokens for each environment:

  1. In Vercel, add environment variables:

    • KEYENV_TOKEN_PRODUCTION - Token scoped to production
    • KEYENV_TOKEN_PREVIEW - Token scoped to staging
  2. Create a build script (scripts/build.sh):

#!/bin/bash
set -e

# Install KeyEnv CLI
curl -fsSL https://keyenv.dev/install.sh | bash
export PATH="$HOME/.keyenv/bin:$PATH"

# Select token and environment based on Vercel deployment type
if [ "$VERCEL_ENV" = "production" ]; then
  export KEYENV_TOKEN="$KEYENV_TOKEN_PRODUCTION"
  keyenv pull -e production
else
  export KEYENV_TOKEN="$KEYENV_TOKEN_PREVIEW"
  keyenv pull -e staging
fi

# Run the build
npm run build
  1. Update package.json:
{
  "scripts": {
    "vercel-build": "bash scripts/build.sh"
  }
}

Next.js Configuration

For Next.js projects, ensure your secrets are available at build time and runtime.

Server Components (App Router)

Secrets in .env are automatically available in server components:

// app/api/route.ts
export async function GET() {
  const apiKey = process.env.API_KEY;
  // Use your secret
  return Response.json({ status: 'ok' });
}

Server Actions

// app/actions.ts
'use server';

export async function submitForm(data: FormData) {
  const apiKey = process.env.API_KEY;
  // Server action has access to secrets
}

Client-Side Variables

Prefix with NEXT_PUBLIC_ for client-side access:

# In KeyEnv, name your secret:
NEXT_PUBLIC_ANALYTICS_ID=UA-123456789
NEXT_PUBLIC_API_URL=https://api.example.com

Then use in client components:

// components/Analytics.tsx
'use client';

export function Analytics() {
  const analyticsId = process.env.NEXT_PUBLIC_ANALYTICS_ID;
  // Available in client bundle
}

Only use NEXT_PUBLIC_ for non-sensitive values. These are embedded in the client bundle and visible to users.


API Reference

KeyEnv uses the Vercel API to manage environment variables when using Native Sync.

Create/Update Variable

POST https://api.vercel.com/v10/projects/{projectId}/env
{
  "key": "DATABASE_URL",
  "value": "postgres://user:pass@host:5432/db",
  "type": "encrypted",
  "target": ["production"]
}

Targets

TargetDescription
productionProduction deployments
previewPreview deployments (PRs, branches)
developmentDevelopment environment (vercel dev)

Comparison: Native Sync vs Build-Time

FeatureNative SyncBuild-Time Pull
Automatic updatesYesNo (requires redeploy)
Setup complexitySimpleModerate
Runtime secretsYesBuild-time only
Audit trailKeyEnv + VercelKeyEnv only
Offline buildsNoYes (if cached)

Recommendation: Use Native Sync for production applications. Use Build-Time Pull when you need more control or have specific requirements.


Troubleshooting

Build fails with "keyenv: command not found"

Ensure the PATH is updated after installation:

export PATH="$HOME/.keyenv/bin:$PATH"

Secrets not available at runtime

If using serverless functions, secrets must be in Vercel's environment variables for runtime access. Build-time secrets are only available during the build.

For runtime access, use Native Sync or sync secrets manually to Vercel.

Sync fails with "Unauthorized"

  1. Reconnect your Vercel account in KeyEnv Settings
  2. Ensure the Vercel token hasn't expired
  3. Check that KeyEnv has access to the target project

Different secrets per branch

Use Vercel's environment variable scoping:

  1. Create branch-specific environments in KeyEnv
  2. Map them to Vercel's Preview environment
  3. Secrets are automatically scoped to the correct branches

Best Practices

  1. Use Native Sync for simplicity - Reduces build complexity and ensures runtime access
  2. Use service tokens - Never use personal credentials in CI/CD
  3. Scope tokens narrowly - Production token should only access production
  4. Don't log secrets - Avoid echo $SECRET in build scripts
  5. Enable auto-redeploy - Keep deployments in sync with secret changes
  6. Use environment mapping - Match KeyEnv environments to Vercel environments

Complete Example

Here's a complete setup for a Next.js application using build-time injection.

Project Structure

my-app/
├── .env.example          # Template (committed)
├── .gitignore            # Includes .env*
├── scripts/
│   └── build.sh          # Build script
├── next.config.js
├── package.json
└── vercel.json

.gitignore

# Environment files
.env
.env.local
.env.production
.env.staging

.env.example

# Database
DATABASE_URL=postgres://user:password@localhost:5432/myapp

# API Keys
API_KEY=your-api-key-here

# Public (client-side)
NEXT_PUBLIC_APP_URL=https://myapp.com
NEXT_PUBLIC_ANALYTICS_ID=UA-123456789

package.json

{
  "name": "my-app",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "vercel-build": "bash scripts/build.sh"
  }
}

scripts/build.sh

#!/bin/bash
set -e

# Install KeyEnv CLI
curl -fsSL https://keyenv.dev/install.sh | bash
export PATH="$HOME/.keyenv/bin:$PATH"

# Pull secrets for the current environment
if [ "$VERCEL_ENV" = "production" ]; then
  keyenv pull -e production
elif [ "$VERCEL_ENV" = "preview" ]; then
  keyenv pull -e staging
else
  keyenv pull -e development
fi

# Build the application
npm run build

Vercel Environment Variables

Add these in your Vercel project settings:

VariableValueEnvironment
KEYENV_TOKENsrv_your_token_hereProduction, Preview

KeyEnv Environments

Create environments in KeyEnv:

EnvironmentSecrets
developmentLocal development values
stagingPreview deployment values
productionProduction values

Deploy

  1. Push to GitHub
  2. Vercel automatically builds using vercel-build script
  3. Secrets are pulled from KeyEnv during build
  4. Application deploys with correct secrets

On this page