According to the docs, Netlify supports next.js through the Essential Build Plugin and manual deployments through a CLI command, but how can I use the two together to build a next.js project in my own CI and deploy only the build output to Netlify?
The plugin page mentions "linking", i.e. it assumes that the project is connected via Git repository and built by netlify, not locally by my own CI.
3 Answers 3
OK, finally got this working. Wrapping it up in case somebody else finds it useful:
- install packages
netlify-cliand@netlify/plugin-nextjs - create
netlify.tomlin the project root as described in this section of the plugin README (make sure to have paths forpublishandfunctions;functionsis required for server-side-rendering and API handlers; both directories will be used for build output during the build) - if using Git, add both paths and
.netlify(another "temp" directory) to.gitignoreto exclude the build output from your repo - important (found the info in the documentation of the former/outdated next-on-netlify project and couldn't deploy without this): add
target: "experimental-serverless-trace"tonext.config.js - for the initial setup:
netlify loginto your account, runnetlify deploy --buildonce, pick a site name - if you want to run the deployment in your CI, configure environment variables
NETLIFY_AUTH_TOKEN(with a "personal access token" from the Netlify UI) andNETLIFY_SITE_ID(displayed in the Netlify UI after choosing a name and successfully completing the first successful deployment) to bypass login and site selection in the future
Comments
Install netlify-cli and @netlify/plugin-nextjs
yarn add -D @netlify/plugin-nextjs
yarn add -D @netlify/plugin-nextjs
Setup the netlify.toml file
[[plugins]]
package = "@netlify/plugin-nextjs"
[build]
command = "yarn next build"
publish = ".next"
Configure the NETLIFY_AUTH_TOKEN and NETLIFY_SITE_ID environment variables
Generate the access token manually in your Netlify user settings for Personal access tokens. This can alternatively be done via the command line. Save the token as a NETLIFY_AUTH_TOKEN environment variable in your terminal settings or in the UI of a Continuous Integration (CI) tool.
The site ID is found in the Netlify UI: Go to Site settings > General > Site details > Site information, and copy the value for API ID, assign the ID to a NETLIFY_SITE_ID environment variable. This can alternatively be done via the netlify link command.
Build and Deploy your Next.js application to Netlify
netlify deploy --build --prod
Docs
- https://docs.netlify.com/configure-builds/file-based-configuration/
- https://github.com/netlify/netlify-plugin-nextjs
- https://docs.netlify.com/cli/get-started/#run-builds-locally
- https://docs.netlify.com/cli/get-started/#manual-deploys
Longer Article
https://paulonteri.com/thoughts/deploy-nextjs-to-netlify-manually
Comments
For me build was not working as I forgot to select runtime to Next.js. Then just build with cleaning the cache.