devnotes.

Authentication & Environment Variables

Environment variables

# .env.local (never commit this file)
DATABASE_URL="postgres://..."
AUTH_SECRET="a-long-random-string"
NEXT_PUBLIC_ANALYTICS_ID="G-XXXXXXX"
  • Variables without the NEXT_PUBLIC_ prefix are only available on the server (Server Components, Route Handlers, Server Actions, middleware) — never sent to the browser. Use these for database URLs, API secrets, and anything sensitive.
  • Variables with the NEXT_PUBLIC_ prefix are inlined into the client JavaScript bundle at build time and are visible to anyone — only use this for genuinely public values like an analytics ID.
// safe: server-only
const dbUrl = process.env.DATABASE_URL;

// only use NEXT_PUBLIC_ for values that are OK to be public
const analyticsId = process.env.NEXT_PUBLIC_ANALYTICS_ID;

Protecting routes

Combine middleware for a fast, early redirect with a server-side check for real authorization:

// middleware.ts — fast, coarse gate
export function middleware(request: NextRequest) {
  const session = request.cookies.get('session');
  if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
// app/dashboard/page.tsx — real check with full data access, inside the render
import { getCurrentUser } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const user = await getCurrentUser();
  if (!user) redirect('/login');
  return <h1>Welcome, {user.name}</h1>;
}

Common authentication approaches

  • Auth.js (NextAuth) — the most widely used authentication library for Next.js; supports OAuth providers (Google, GitHub), credentials, and database sessions.
  • Third-party platforms — Clerk, Auth0, and Supabase Auth provide hosted authentication with prebuilt Next.js integrations.
  • Roll your own — sign a session cookie (e.g. with jose for JWTs), verify it in middleware and Server Components; more control, more responsibility for security correctness.

A note on secrets in Server Actions and Route Handlers

Because Server Actions and Route Handlers run only on the server, it's safe to reference secret environment variables directly inside them — but always double-check that a function marked 'use server' doesn't accidentally leak a secret value back to the client in its return value.

Next.js Authentication Patterns and Environment Variables | DevNotes