Ship it safely
Authorise close to the data, keep proxy light, keep secrets server-side, optimise images, fonts and scripts, and deploy with monitoring.
- SecuritySessions, data access layer and proxy.
- PerformanceImages, fonts, scripts and bundles.
- OperationsDeployment, env vars and error tracking.
Production questions separate people who built a demo from people who shipped. Interviewers ask how you protect pages and actions, what runs before a request, how secrets stay secret, and how you deploy and keep the app fast.
1. How do you implement authentication in Next.js?
Use a proven library (Auth.js, Clerk, Supabase Auth, or your provider's SDK) with secure, HttpOnly session cookies. Check the session in Server Components (to choose what to render), in every Server Action and Route Handler (to authorise), and optionally in the proxy for fast redirects. A data access layer that checks permissions centrally keeps it consistent.
// lib/dal.ts — one place that knows who is allowed to read what
import 'server-only';
import { cache } from 'react';
export const getCurrentUser = cache(async () => {
const session = await getSession(); // reads the session cookie
if (!session) redirect('/login');
return session.user;
});
export async function getMyOrders() {
const user = await getCurrentUser();
return db.order.findMany({ where: { userId: user.id } });
}2. What does proxy (middleware) do, and what changed in Next.js 16?
It runs before a request completes — redirects, rewrites, headers, locale detection, A/B tests and quick auth redirects. In Next.js 16 the file convention is proxy.ts (the old middleware.ts name is deprecated). Keep it fast and light; do real authorisation next to the data, because proxy alone is not a security boundary.
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server';
export function proxy(req: NextRequest) {
const hasSession = req.cookies.has('session');
if (!hasSession && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
export const config = { matcher: ['/dashboard/:path*'] };3. How do environment variables work?
Variables in .env files are server-only by default. Only names prefixed NEXT_PUBLIC_ are inlined into the browser bundle at build time — never prefix secrets. Validate required variables at startup (for example with a Zod schema) so a missing key fails fast.
4. How does next/image improve performance?
It serves resized images in modern formats (WebP/AVIF), lazy-loads by default, requires width and height (or fill) to prevent layout shift, generates responsive srcsets with sizes, and supports priority/preload for the main above-the-fold image.
import Image from 'next/image';
<Image src="/hero.webp" alt="Students practising interviews" width={1200} height={630} priority
sizes="(max-width: 768px) 100vw, 1200px" />5. How do you load fonts and third-party scripts efficiently?
next/font self-hosts Google or local fonts at build time with no layout shift and no request to Google from the user's browser. next/script controls loading strategy (afterInteractive, lazyOnload) so analytics and widgets do not block rendering.
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
export default function RootLayout({ children }) {
return <html lang="en" className={inter.className}><body>{children}</body></html>;
}6. How do you deploy a Next.js app?
On Vercel with zero configuration, or anywhere Node runs: next build then next start, ideally with output: 'standalone' in a Docker image. Static-only sites can use output: 'export'. Configure environment variables per environment, a CDN for static assets, and a cache handler shared across instances when self-hosting several servers.
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine
WORKDIR /app
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
CMD ["node", "server.js"]7. How do you find and fix performance problems?
Measure Core Web Vitals (Vercel Speed Insights, Lighthouse, real-user monitoring), inspect bundle size with the bundle analyzer, move work to Server Components, lazy-load heavy client components with next/dynamic, cache data, stream slow sections, and optimise images and fonts.
8. How do you handle errors and logging in production?
Use error.tsx boundaries per segment and global-error.tsx for the root, return friendly messages, report errors to a monitoring service (Sentry or similar) via the instrumentation.ts hooks, and log structured data on the server without secrets or personal data.
Remember
Key points
- Authorise in actions and handlers
Proxy is not the security boundary.
- NEXT_PUBLIC_ = public
Never for secrets.
- next/image and next/font
Fewer bytes and no layout shift.
- standalone output
Small Docker images for self-hosting.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 Where can proxy (middleware) run? Intermediate
It runs before routes on the server; in recent versions it can use the Node.js runtime, so most Node APIs are available, but it should stay fast because it runs on many requests.
-
2 How do you add security headers? Intermediate
Configure
headers()in next.config (CSP, X-Frame-Options or frame-ancestors, Referrer-Policy) or set them in proxy for nonces. -
3 How do you rate-limit an API route? Advanced
Use a shared store (Redis/Upstash) keyed by user or IP inside the Route Handler or proxy, returning 429 with Retry-After.
-
4 What does next/dynamic do? Basic
It lazy-loads a client component (optionally with ssr: false) so heavy code such as charts or maps loads only when needed.
-
5 How do you generate a sitemap? Basic
Add
app/sitemap.tsthat returns URL entries; Next.js serves it at /sitemap.xml. robots.ts works the same way. -
6 What is instrumentation.ts? Advanced
A file whose register() runs once when the server starts — for setting up OpenTelemetry tracing and error reporting.