Skip to main content
skill CX Codex

nextjs · bobmatnyc — Claude Code skill: Next.js environment variables

Maps Next.js environment variables across .env* files, shows which one wins, and covers Vercel deployment.

MIT 212 installs ★ 80 updated 2026-07-18

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add bobmatnyc/claude-mpm-skills --skill nextjs -a claude-code
Open on GitHub

What nextjs does

The skill walks through how a Next.js project splits config across .env, .env.local, .env.development, .env.production and the matching .local files. Load order runs from .env.$(NODE_ENV).local down to plain .env, with .env.local skipped under test. Two definitions of DATABASE_URL therefore resolve to the more specific file.

Anything prefixed NEXT_PUBLIC_ ships to the browser. Everything else stays on the server, reachable from API routes and getServerSideProps. A key placed in NEXT_PUBLIC_* is readable by anyone who opens devtools. Those public values get baked in at build time, so editing them in the Vercel dashboard does nothing until you run vercel --prod again.

Sample .env files come with it, plus a check routine built on python scripts/validate_env.py .env.local --framework nextjs, a diff against .env.example, a leak scan via python scripts/scan_exposed.py --check-gitignore, and python scripts/sync_secrets.py --platform vercel --compare. The scripts are Python.

What it helps with

  • sort config across .env, .env.local and .env.production
  • trace which file overrides a value in production
  • keep secrets out of NEXT_PUBLIC_* before the build ships
  • diff .env.local against .env.example
  • push local secrets into Vercel variables

Example prompts for the agent

  • Lay out my Next.js env files: what belongs in .env, .env.local and .env.production.
  • Why did production pick DATABASE_URL from .env instead of .env.production.local?
  • Run scripts/validate_env.py on .env.local and compare it with .env.example.

How to install nextjs

1Skills CLI (Vercel)

npx skills add bobmatnyc/claude-mpm-skills --skill nextjs -a claude-code

2Manually: put the files in place

~/.claude/skills/nextjs/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/nextjs/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about nextjs

How do I install nextjs in Claude Code?

Run npx skills add bobmatnyc/claude-mpm-skills --skill nextjs -a claude-code. The skill file lands at ~/.claude/skills/nextjs/SKILL.md.

What does nextjs do?

It is a reference on Next.js environment variables: the .env* load order, the split between NEXT_PUBLIC_* and server-side values, and Vercel deployment. It adds no slash command of its own.

Do I need to redeploy after changing a NEXT_PUBLIC_* variable?

Yes. Those values are baked into the bundle at build time, so run vercel --prod after editing them in the Vercel dashboard. Otherwise the browser keeps the old ones.

Source text

SKILL.md · MIT
---
name: nextjs
description: Next.js environment variable management with file precedence, variable types, and deployment configurations. Use when configuring Next.js applications, managing environment-specific settings, or deploying to Vercel/Railway/Heroku.
user-invocable: false
disable-model-invocation: true
progressive_disclosure:
  entry_point:
    summary: "Next.js environment variable management with file precedence, variable types, and deployment configurations. Use when configuring Next.js applications, managing environment-specific settings, or de..."
    when_to_use: "When working with nextjs-env-variables or related functionality."
    quick_start: "1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation."
---
# Next.js Environment Variable Structure

Complete guide to Next.js environment variable management.

## File Structure

```
my-nextjs-app/
├── .env                      # Shared defaults (committed)
├── .env.local               # Local secrets (gitignored)
├── .env.development         # Development defaults (committed)
├── .env.development.local   # Local dev overrides (gitignored)
├── .env.production          # Production defaults (committed)
├── .env.production.local    # Production secrets (gitignored)
├── .env.test                # Test environment (committed)
└── .env.example             # Documentation (committed)
```

## File Precedence

Next.js loads files in this order (higher = higher precedence):

1. `.env.$(NODE_ENV).local` (e.g., `.env.production.local`)
2. `.env.local` (not loaded in test environment)
3. `.env.$(NODE_ENV)` (e.g., `.env.production`)
4. `.env`

**Example**: In production, if `DATABASE_URL` is defined in both `.env` and `.env.production.local`, the value from `.env.production.local` wins.

## Variable Types

### Client-Side Variables (NEXT_PUBLIC_*)

Exposed to the browser. Must prefix with `NEXT_PUBLIC_`.

```bash
# .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_ANALYTICS_ID=UA-123456789
NEXT_PUBLIC_SITE_NAME=My Awesome Site
NEXT_PUBLIC_ENABLE_FEATURE_X=true
```

**Access in code**:
```javascript
// Works in both client and server
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

// Usage in components
export default function MyComponent() {
  return <div>API: {process.env.NEXT_PUBLIC_API_URL}</div>;
}
```

**⚠️ Security Warning**: NEVER put secrets in `NEXT_PUBLIC_*` variables!

```bash
# ❌ WRONG - Secret exposed to browser
NEXT_PUBLIC_API_SECRET=sk_live_abc123

# ✅ CORRECT - Secret only on server
API_SECRET=sk_live_abc123
```

### Server-Side Variables

Only available in server-side code (API routes, getServerSideProps, etc.).

```bash
# .env.local
DATABASE_URL=postgres://localhost:5432/mydb
JWT_SECRET=super-secret-jwt-key-do-not-expose
STRIPE_SECRET_KEY=sk_live_abc123
SMTP_PASSWORD=email-password-here
```

**Access in code**:
```javascript
// ✅ Works in API routes
export default async function handler(req, res) {
  const dbUrl = process.env.DATABASE_URL;
  // Use dbUrl...
}

// ✅ Works in getServerSideProps
export async function getServerSideProps() {
  const secret = process.env.JWT_SECRET;
  // Use secret...
}

// ❌ Does NOT work in components (browser)
export default function MyComponent() {
  const dbUrl = process.env.DATABASE_URL; // undefined!
}
```

## Example Files

### .env (Committed - Shared Defaults)

```bash
# Shared defaults for all environments
NEXT_PUBLIC_APP_NAME=My Next.js App
NEXT_PUBLIC_DEFAULT_LOCALE=en

# Database (overridden in .env.local)
DATABASE_URL=postgres://localhost:5432/dev

# External services (no secrets)
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_abc123
```

### .env.local (Gitignored - Local Secrets)

```bash
# Local development secrets
DATABASE_URL=postgres://localhost:5432/mylocal
JWT_SECRET=dev-jwt-secret-change-in-production
STRIPE_SECRET_KEY=sk_test_local_key

# Local overrides
NEXT_PUBLIC_API_URL=http://localhost:4000/api
```

### .env.production (Committed - Production Defaults)

```bash
# Production environment defaults
NEXT_PUBLIC_API_URL=https://api.production.com
NEXT_PUBLIC_ANALYTICS_ID=UA-PROD-123456

# These will be overridden by platform env vars
DATABASE_URL=set-this-in-vercel
JWT_SECRET=set-this-in-vercel
```

### .env.example (Committed - Documentation)

```bash
# Copy this to .env.local and fill in actual values

# Client-side (browser accessible)
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_ANALYTICS_ID=your-analytics-id
NEXT_PUBLIC_SITE_NAME=Your Site Name

# Server-side (secrets)
DATABASE_URL=postgres://user:password@host:5432/database  # pragma: allowlist secret
JWT_SECRET=your-jwt-secret-32-chars-minimum
STRIPE_SECRET_KEY=sk_live_your_stripe_key
SMTP_HOST=smtp.example.com
SMTP_PORT=587
[email protected]
SMTP_PASSWORD=your-smtp-password
```

## Common Patterns

### Database Configuration

```bash
# Development (.env.local)
DATABASE_URL=postgres://localhost:5432/myapp_dev

# Production (Vercel Environment Variables)
DATABASE_URL=postgres://user:pass@prod-host:5432/myapp_prod  # pragma: allowlist secret
```

### API Keys

```bash
# Public keys (client-side)
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_abc123

# Secret keys (server-side only)
STRIPE_SECRET_KEY=sk_live_xyz789
```

### Feature Flags

```bash
# Toggle features
NEXT_PUBLIC_ENABLE_DARK_MODE=true
NEXT_PUBLIC_ENABLE_BETA_FEATURES=false
```

## Deployment to Vercel

### Step 1: Add Environment Variables in Vercel

1. Go to Project Settings → Environment Variables
2. Add each variable:
   - **Key**: `DATABASE_URL`
   - **Value**: `postgres://...`
   - **Environments**: Production, Preview, Development

### Step 2: Separate Client vs Server Variables

Vercel automatically exposes `NEXT_PUBLIC_*` variables at build time.

```bash
# Vercel automatically handles:
NEXT_PUBLIC_API_URL=https://api.example.com  # ✅ Exposed to browser

# Server-only:
DATABASE_URL=postgres://...  # ✅ Not exposed to browser
```

### Step 3: Rebuild After Changing NEXT_PUBLIC_ Variables

⚠️ Important: `NEXT_PUBLIC_*` variables are **baked into the build** at build time.

If changing them in Vercel, **redeploy** is required:

```bash
vercel --prod
```

## Validation Workflow

### 1. Validate Local Environment

```bash
# Check structure
python scripts/validate_env.py .env.local --framework nextjs

# Compare with .env.example
python scripts/validate_env.py .env.local --compare-with .env.example

# Check for security issues
python scripts/scan_exposed.py --check-gitignore
```

### 2. Check File Precedence

```bash
# List all .env files
ls -la .env*

# Validate each
for file in .env*; do
  echo "=== $file ==="
  python scripts/validate_env.py $file --framework nextjs
done
```

### 3. Sync to Vercel

```bash
# Compare local vs Vercel
python scripts/sync_secrets.py --platform vercel --compare

# Sync (dry-run first)
python scripts/sync_secrets.py --platform vercel --sync --dry-run

# Actually sync
python scripts/sync_secrets.py --platform vercel --sync --confirm
```

## Common Issues

### Issue: Variable Undefined in Browser

**Symptom**: `process.env.MY_VAR` is `undefined` in component.

**Solution**: Add `NEXT_PUBLIC_` prefix:

```bash
# ❌ Wrong
API_URL=https://api.example.com

# ✅ Correct
NEXT_PUBLIC_API_URL=https://api.example.com
```

### Issue: Changed Variable Not Reflected

**Symptom**: Changed `NEXT_PUBLIC_*` variable in Vercel, but app still uses old value.

**Solution**: Redeploy (variables are baked into build):

```bash
vercel --prod
```

### Issue: Works Locally, Not in Production

**Symptom**: App works with `.env.local`, fails in production.

**Solution**: Ensure all variables from `.env.local` are set in Vercel:

```bash
# Compare
python scripts/sync_secrets.py --platform vercel --compare

# Find missing vars and add them in Vercel UI
```

## Security Checklist

- [ ] `.env.local` in `.gitignore`
- [ ] `.env.*.local` in `.gitignore`
- [ ] No secrets in `NEXT_PUBLIC_*` variables
- [ ] No `.env` files committed with real secrets
- [ ] `.env.example` has structure, not actual values
- [ ] Secrets set directly in Vercel (not in committed files)

## References

- [Next.js Environment Variables Documentation](https://nextjs.org/docs/basic-features/environment-variables)
- [Vercel Environment Variables](https://vercel.com/docs/environment-variables)

---

**Related**: [validation.md](../references/validation.md) | [security.md](../references/security.md) | [frameworks.md](../references/frameworks.md)

## Related Skills

When using Nextjs, these skills enhance your workflow:
- **react**: Core React patterns and hooks for Next.js components
- **tanstack-query**: Server-state management with App Router and Server Components
- **drizzle**: Type-safe ORM for Next.js server actions and API routes
- **prisma**: Alternative ORM with excellent Next.js integration
- **test-driven-development**: Testing Next.js App Router, Server Components, and API routes

[Full documentation available in these skills if deployed in your bundle]

© bobmatnyc · MIT · bobmatnyc/claude-mpm-skills

Similar skills

All skills for Frontend and UI →

nextjs by other authors comes first.

nextjs official Vercel Labs Guidance for building and debugging Next.js App Router projects. Use it to work through routing, Server Components, data fetching, and rendering choices. CX Codex GP ChatGPT +1 50installs nextjs pproenca This skill guides Next.js 16 App Router work, from caching and Server Components to routing and codebase reviews. CX Codex +1 1,200installs nextjs PyModel Skill for Claude Code, Codex, and Cursor enforces Next.js 16 App Router standards. It guides caching strategies, server components, and routing patterns. CX Codex +1 621installs nextjs Claude Skills Maintainers Skill for Next.js 16 and React 19.2 with App Router, Server Components, Server Actions, and caching patterns. Handles migration from version 15, async params errors, and Partial Prerendering setup. CX Codex +1 299installs nextjs ulpi-io Guides coding agents through Next.js App Router tasks while respecting the project's installed framework release and internal architecture. CX Codex +1 182installs vercel-env-sync davila7 vercel-env-sync synchronizes environment variables between local .env files and Vercel deployments via the Vercel CLI. Handles pulling, pushing, backups, and format checks. CX Codex +1 406installs vercel-environment-sync davila7 vercel-environment-sync — a Claude Code hook that watches .env files on every save and validates variables before syncing with Vercel. Triggers on Write, Edit, and MultiEdit tool calls that touch .env files. 363installs nextjs-on-cloudflare cloudflare nextjs-on-cloudflare — a skill for deploying Next.js apps to Cloudflare Workers via vinext. Use for new projects, migrating existing apps, or choosing between vinext and OpenNext. CX Codex +1 60,100installs nextjs-deployment giuseppe-trisciuoglio nextjs-deployment provides production deployment patterns for Next.js. Sets up multi-stage Dockerfiles, GitHub Actions workflows, health checks, and OpenTelemetry instrumentation. CX Codex +1 3,900installs vercel-deployment sickn33 vercel-deployment — a Claude Code skill that gives the agent a procedure for deploying Next.js apps to Vercel. It kicks in when the task mentions vercel, deploy, production, or environment variables. CX Codex +1 1,800installs vercel-deployments devops-skills vercel-deployments — a skill for deploying frontend and full-stack apps on Vercel: previews, edge functions, environment variables and production guardrails. CX Codex +1 351installs

From the same set143

The whole set →
prisma Reference patterns for Prisma ORM in TypeScript projects: schema design, migrations, nested queries, and Next.js setup. CX Codex +1 222installs code-quality code-quality reviews Python for exception, comparison, import, constant, and dead-local issues. Use it for pull-request review or a self-check before committing. CX Codex +1 221installs react-core react-core is a Claude Code skill that gives an agent a React fundamentals reference for working with components and JSX, props and state, hooks, composition, lists, and controlled inputs. CX Codex +1 220installs supabase Provides patterns for configuring @supabase/supabase-js, querying Postgres via PostgREST, and setting up auth flows in Next.js, React, or Vue apps. CX Codex +1 219installs tauri A skill for advanced Tauri event patterns: bidirectional communication, streaming data, and window-to-window messaging. Use it when building desktop apps that need real-time updates between Rust backend and TypeScript frontend. CX Codex +1 210installs react-advanced react-advanced is a Claude Code skill for React 19 development, covering React Compiler adoption, Actions, concurrent rendering, and modern component architecture. CX Codex +1 209installs react-hooks-composition react-hooks-composition — a skill with patterns for composing React hooks around SWR, debounced search, and context providers. Use it when building data-fetching hooks or managing async UI states. CX Codex +1 206installs code-quality-scoring code-quality-scoring scores codebase health, technical debt remediation effort, and cloud readiness. Useful when assessing entire applications before refactoring. CX Codex +1 206installs

Project sponsors

Companies that keep this analytics open