Auth, deployment and production
You've built the app. This last lesson covers adding authentication safely, deploying it, and the production checklist professional teams run through before launch.
Authentication: three layers
Auth has three jobs:
- Authentication: who are you? (sign-in, sessions)
- Session management: remembering you between requests (usually a secure, HTTP-only cookie)
- Authorization: what are you allowed to do or see?
Most teams use a library or service rather than building auth from scratch:
| Option | Type |
|---|---|
| Auth.js (NextAuth), Better Auth | Open-source libraries you host |
| Clerk, Auth0, Supabase Auth, Firebase Auth | Hosted services with ready-made UI |
Protect data where it's accessed
The most important rule: check authorization close to the data, in Server Components, Server Actions and Route Handlers, not only in Proxy or the UI. A common pattern is a data access layer:
// lib/dal.ts
import 'server-only';
import { cache } from 'react';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export const verifySession = cache(async () => {
const token = (await cookies()).get('session')?.value;
const session = await decryptAndValidate(token); // your auth library
if (!session) redirect('/login');
return session; // { userId, role }
});
export async function getMyOrders() {
const { userId } = await verifySession(); // every data function checks
return db.order.findMany({ where: { userId } }); // users only ever see their own orders
}// app/orders/page.tsx
import { getMyOrders } from '@/lib/dal';
export default async function OrdersPage() {
const orders = await getMyOrders();
return <ul>{orders.map((o) => <li key={o.id}>#{o.id}: ${o.total}</li>)}</ul>;
}- Use HTTP-only, Secure, SameSite cookies for sessions (never
localStoragefor tokens). - Hash passwords with bcrypt or argon2, or better, offer passkeys and OAuth sign-in.
- Return DTOs (only the fields the UI needs), never whole database rows with password hashes.
Environment variables
# .env.local — never commit this file
DATABASE_URL="postgres://…"
AUTH_SECRET="…"
NEXT_PUBLIC_SITE_URL="https://learntocode.example" # NEXT_PUBLIC_ = exposed to the browser- Variables without
NEXT_PUBLIC_are server-only. NEXT_PUBLIC_values are inlined into the browser bundle at build time, so never put secrets there.- Set production values in your hosting dashboard, not in files.
Deploying
Option 1: a managed platform (easiest)
Push to GitHub, import the repo on a platform that supports Next.js (Vercel, Netlify and others), and set the environment variables. Every push to main deploys to production, and every pull request gets a preview URL.
Option 2: self-host with Node.js
npm run build
npm run start # serves on port 3000Put it behind a reverse proxy like Nginx, and keep it running with a process manager or a container.
Option 3: Docker
Enable the standalone output, which bundles only the files needed at runtime:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = { output: 'standalone' };
export default nextConfig;FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"](See the Docker track's multi-stage builds lesson for why this is structured this way.)
Option 4: static export
If your site needs no server at all (no Server Actions, no request-time data), output: 'export' produces plain HTML/CSS/JS that can be hosted anywhere, even on a CDN or GitHub Pages.
Production checklist
Performance
- Use Server Components by default; keep
'use client'at the leaves - Cache with
'use cache'+cacheLifewhere the data allows; stream the rest with<Suspense> -
next/imagefor images,next/fontfor fonts - Check bundle size, and lazy-load heavy client components with
next/dynamic - Measure Core Web Vitals (Lighthouse, or your host's analytics)
Security
- Auth checks inside every Server Action, Route Handler and data access function
- Validate every input (Zod)
- No secrets in
NEXT_PUBLIC_variables or client code;import 'server-only'on sensitive modules - Security headers / Content Security Policy
Reliability and UX
-
error.tsx,global-error.tsx,not-found.tsxandloading.tsxstates - Error tracking (Sentry or similar) and logging
- Metadata, sitemap, robots, Open Graph images
- Accessibility pass (keyboard, labels, contrast)
Process
- CI runs
tsc --noEmit, lint, tests andnext buildon every PR - Preview deployments for PRs; database migrations automated
🎓 Next.js track complete!
You can build full-stack React apps with the App Router: layouts, Server and Client Components, data fetching and streaming, Route Handlers, Server Actions, explicit caching, metadata, errors, Proxy, auth and deployment.
Capstone project
Build and deploy a mini store:
- Product list and detail pages (
/products,/products/[slug]) with cached data andgenerateMetadata - A cart in a Client Component with Context
- A checkout form using a Server Action with Zod validation and
useActionState /api/ordersRoute Handlers for a future mobile app- Auth-protected
/account/ordersusing a data access layer - Loading, error and not-found states; a sitemap
- Deploy it, and share the URL!
1.Where should authorization checks live?
2.What happens to an environment variable named NEXT_PUBLIC_API_KEY?