How to Deploy Next.js to Netlify: Step-by-Step Guide
To deploy a
Next.js app to Netlify, first configure your app for static export by adding next export in your package.json scripts. Then, connect your GitHub repo to Netlify, set the build command to npm run build && npm run export, and the publish directory to out. Netlify will build and host your static Next.js site automatically.Syntax
Deploying Next.js to Netlify involves these key parts:
- Build Command: Runs your Next.js build and export scripts.
- Publish Directory: The folder Netlify serves, usually
outafter export. - Static Export: Next.js converts your app to static files using
next export.
json
{
"scripts": {
"build": "next build",
"export": "next export",
"start": "next start"
}
}Example
This example shows a minimal package.json setup and Netlify build settings to deploy a Next.js app as a static site.
json
{
"name": "my-next-app",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next export",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "latest",
"react-dom": "latest"
}
}
// Netlify build settings:
// Build command: npm run build && npm run export
// Publish directory: outOutput
Netlify builds your Next.js app, runs the export, and serves the static files from the 'out' folder.
Common Pitfalls
Common mistakes when deploying Next.js to Netlify include:
- Not using
next exportwhich causes dynamic features to fail. - Setting the wrong publish directory (should be
outafter export). - Using server-side features that require Node.js server, which Netlify static hosting does not support.
Always ensure your app can run as a static site before deploying.
json
"build": "next build && next export"
Quick Reference
| Step | Description | Value/Command |
|---|---|---|
| 1 | Add export script to package.json | "export": "next export" |
| 2 | Set Netlify build command | npm run build && npm run export |
| 3 | Set Netlify publish directory | out |
| 4 | Push code to GitHub and connect repo to Netlify | — |
| 5 | Trigger deploy on Netlify | Automatic on push |
Key Takeaways
Use next export to convert your Next.js app into static files for Netlify.
Set Netlify's build command to 'npm run build && npm run export' and publish directory to 'out'.
Netlify hosts static sites; avoid server-side Next.js features that need Node.js runtime.
Connect your GitHub repo to Netlify for automatic deploys on code push.
Test your app locally with 'next export' to ensure it works as a static site before deploying.