What Next.js adds to React
npx create-next-app@latestAsked in interviews
AskedWhat are the main benefits of using Next.js over Create React App?app/ with a page.js file becomes a URL.'use client'. Server Component code never reaches the browser.next build, until it reads request data such as cookies() or searchParams. Then it renders on every request.pages/ to a URL and fetches data in getStaticProps or getServerSideProps . Both routers can run in one app.npx create-next-app@latestAsked in interviews
AskedWhat are the main benefits of using Next.js over Create React App?app/blog/page.js pages/blog.jsTrapLinks between pages and app routes do a hard navigation, a full reload that loses client state.
pages/_app.jsIts state survives navigation.pages/_document.js Server only, no event handlers.app/layout.jsRenders <html> and <body>.TrapThe <Head /> in _document.js isn't next/head. Set page titles with next/head.
app/blog/[slug]app/docs/[...slug] slug is an array.public/logo.pngTrap[...slug] doesn't match plain /docs. Use [[...slug]], which does, with slug undefined.
await paramsuseParams()useSearchParams() router.query<Form action="/search"> From next/form.Traprouter.query starts empty on a prerendered Pages Router page, so id is undefined at first.
<Link href="/about">router.push(url) useRouter from next/navigation.prefetch={false} TrapPrefetching runs only in production, never in next dev.
async redirects()308 and 307 keep the method.async rewrites()app/[lang]/page.js Proxy redirects to a locale.i18n: { locales, defaultLocale }layout.jsKeeps state on navigation.template.jsRemounts with a new key.loading.jsThe page's Suspense fallback.TrapA layout doesn't re-render on navigation, so never rely on it alone for an auth check.
error.jsMust be a Client Component.global-error.jsnotFound()Renders not-found.js.pages/404.jspages/500.jsTrapAn error.js doesn't catch errors in the layout of its own folder.
export const metadatagenerateMetadata() app/sitemap.jsapp/manifest.tsPlus a service worker.TrapMetadata exports work only in Server Components. Use generate when the title needs fetched data.
await db.query()Read a database or a secret keyuseStateonClickUse state, event handlers or windowuseContextProvide or read React contextAsked in interviews
AskedWhat are Server Components and how do they work in App Router?'use client'At the top, above the imports.window or Date in render, or a div inside a p.useEffect(() => setIsClient(true), [])suppressHydrationWarning TrapClient Components still render to HTML on the server. 'use client' doesn't mean browser only.
TrapA module-level store on the server is shared by all requests. Make one per request for user data.
revalidate: 60ISRRebuild static pages after deployTipSSG is fastest, but only as fresh as the last build. SSR is always fresh, but each request waits. CSR is weak for SEO.
await getPosts()In any async Server Component.getStaticPropsAdd revalidate for ISR.getServerSideProps Gets req and params.TrapgetStaticProps can't read the request. Cookies, auth and per-user data need get.
getStaticPathsPair it with getStaticProps.fallback: falsefallback: trueCheck router.isFallback .fallback: 'blocking'generateStaticParams() TrapNeither true nor 'blocking' updates a built page. Add revalidate for fresh content.
useEffect, in a Client Component.useSWR(key, fetcher)controller.abort() In the effect cleanup.npm install @next/mdxAdd mdx to pageExtensions.global in dev.fetch on the server, Apollo on the client.TrapRendering CMS HTML with dangerously risks XSS. Sanitize it first.
{ next: { revalidate: 60 } }revalidatePath(path) revalidateTag(tag, 'max')Refreshes in the background.updateTag(tag)Only inside a Server Action.TrapSince Next.js 15, fetch results aren't cached by default. Opt in with cache: 'force-cache'.
Asked in interviews
AskedHow do you implement server-side caching in Next.js?'use cache'cacheLife('hours') cacheTag('posts') unstable_cache() TrapCached code can't read cookies() or headers(). Read them outside and pass the values in.
Asked in interviews
AskedHow do you implement advanced caching strategies in Next.js?app/api/users/route.js export function POST()Unexported methods get 405.await req.json()req.nextUrl.searchParams pages/api/users.js Check req.method.TrapA route.js can't sit in the same folder as a page.js.
await req.formData()Store it in S3, not on disk.bodyParser: falseThen parse with formidable.Access-Control-Allow-* and answer OPTIONS.Trapfetch doesn't reject on a 404 or 500. The client must check response.ok.
'use server'<form action={save}>Works before JavaScript loads.TrapAnyone can call an action with a direct POST. Check auth and validate input inside it.
after(() => log())app.getRequestHandler() It can't use standalone output.basePath: '/blog'TrapNever start a queue worker in a module your routes import. It would start in every web instance.
Asked in interviews
AskedHow do you implement background jobs in Next.js?proxy.jsWas middleware.js before 16.matcher: '/admin/:path*'NextResponse.redirect(url) TrapWithout a matcher, Proxy runs on every request, static files and images included.
redirect('/login') Check the session first.[...nextauth].js Then call useSession().TrapNever rely on Proxy alone. Check the session again where the data is read.
import 'server-only'async headers()A CSP and X-Frame-Options.Retry-After.import './globals.css'In the root layout.pages/_app.jsThe only file allowed to import it.Button.module.css Use it as styles.primary.TrapNext.js doesn't remove global CSS as you navigate, so rules from two pages can clash.
npm install -D tailwindcss @tailwindcss/postcss npm install sass.module.scss files are scoped.<style jsx>Ships with Next.js.TipThe docs recommend Tailwind. It builds plain CSS, so Server Components can use it.
<Image src={hero} alt="Hero" />preloadWas priority before 16.next/font/google next/font/localTrapNext.js 16 allows only quality={75} unless you list more in images..
dynamic(() => import('./Chart')) { ssr: false }Client Components only.useReportWebVitals TrapINP replaced FID as a Core Web Vital. Report INP, since web-vitals removed onFID.
ANALYZE=true npm run build -- --webpackoptimizePackageImports Plus named ES module imports.react-windowRenders only visible rows.IntersectionObserver next.config.jsAlso .mjs or .ts.NEXT_PUBLIC_API_URL Others stay server-only.TrapNext.js inlines NEXT_PUBLIC_ values at build time. Never put a secret in one.
next buildnext startoutput: 'standalone'vercel --prodTipnext build prerenders every route it can, and fails on type errors.
.tsx, then run next dev.NextApiResponse<User[]> RouteContext<'/users/[id]'> Trapreq.body is typed any. Validate it at runtime, for example with Zod.
require('next/jest') It mocks CSS, images and fonts.await GET(new Request(url))createMocks({ method: 'GET' })next build --webpackNeeded for custom webpack.webpack: (config) => configconsole.log with SWCcompiler: { removeConsole: true }TrapA Babel config switches every file from SWC to Babel, which is about 17 times slower.
Asked in interviews
AskedHow do you customize the webpack configuration in Next.js?Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in