Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NX
Next.js
0/10 completed
Beginner
Why Next.js?Pages, layouts and routingLinks, images and fonts
Intermediate
Server and Client ComponentsFetching data and streamingRoute Handlers (API routes)Forms and Server Actions
Advanced
Caching and revalidationMetadata, SEO, errors and Proxy
Pro
Auth, deployment and production
Tracks / Next.js / Pro

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:

  1. Authentication: who are you? (sign-in, sessions)
  2. Session management: remembering you between requests (usually a secure, HTTP-only cookie)
  3. 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:

ts
// 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
}
tsx
// 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 localStorage for 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

bash
# .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

bash
npm run build
npm run start        # serves on port 3000

Put 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:

ts
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = { output: 'standalone' };
export default nextConfig;
dockerfile
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' + cacheLife where the data allows; stream the rest with <Suspense>
  • next/image for images, next/font for 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.tsx and loading.tsx states
  • 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 and next build on 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:

  1. Product list and detail pages (/products, /products/[slug]) with cached data and generateMetadata
  2. A cart in a Client Component with Context
  3. A checkout form using a Server Action with Zod validation and useActionState
  4. /api/orders Route Handlers for a future mobile app
  5. Auth-protected /account/orders using a data access layer
  6. Loading, error and not-found states; a sitemap
  7. Deploy it, and share the URL!
✎ Check your understanding

1.Where should authorization checks live?

2.What happens to an environment variable named NEXT_PUBLIC_API_KEY?

← Metadata, SEO, errors and Proxy