Next.js - How to Test a Build Locally to Detect Differences

3 replies
Last updated: Nov 10, 2020
Coming to Next from Gatsby. Is there a equivalent for testing a build locally to detect for differences?
For Gatsby I’d run
gatsby build && gatsby serve
AI Update

The Next.js equivalent to gatsby build && gatsby serve is:

npm run build && npm run start

or if you're using pnpm/yarn:

pnpm build && pnpm start
# or
yarn build && yarn start

This works the same way as your Gatsby workflow:

  • npm run build (runs next build) creates an optimized production build
  • npm run start (runs next start) serves that production build locally on http://localhost:3000 by default

This lets you test the production build locally to catch any differences between development and production mode before deploying. Common differences you might catch include:

  • Client-side vs server-side rendering issues
  • Environment variable problems (make sure you have the right .env.production or .env.local files)
  • Image optimization differences
  • API route behavior
  • Static generation vs server-side rendering issues
  • Missing generateStaticParams or data fetching problems

If you're also running Sanity Studio alongside your Next.js app (like in a monorepo), you can test a production build of the Studio locally with npm run build in the Studio directory, as mentioned in the Sanity Studio development docs.

The production build is important to test because Next.js behaves quite differently in development mode (with features like Fast Refresh, more verbose error messages, and unoptimized bundles) compared to the optimized production build that gets deployed.

I believe
next build && next start
is the equivalent (CLI docs )
next start
starts the application in production mode. The application should be compiled with
next build
first.
Perfect.
Yes, was writing exactly the same. If you want to test static exports, you’d run
next build && next export
and then serve the contents from your build dir 🙂

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?