Deploying Nextjs Sites with Netlify
Turns out, there's some setup needed to deploy a Nextjs site to Netlify.
Build process
Netlify provides a next-on-netlify
utility that generates the public files needed, when the site is built from Nextjs. To use it, first add the library to dev dependencies:
yarn add -D next-on-netlify
Then create this Node script next-on-netlify.js:
#!/usr/bin/env node
const { program } = require("commander");
program
.option(
"--max-log-lines [number]",
"lines of build output to show for each section",
50
)
.parse(process.argv);
const { logTitle } = require("./lib/helpers/logger");
const prepareFolders = require("./lib/steps/prepareFolders");
const copyPublicFiles = require("./lib/steps/copyPublicFiles");
const copyNextAssets = require("./lib/steps/copyNextAssets");
const setupPages = require("./lib/steps/setupPages");
const setupRedirects = require("./lib/steps/setupRedirects");
prepareFolders();
copyPublicFiles();
copyNextAssets();
setupPages();
setupRedirects();
logTitle("✅ Success! All done!");
Netlify configurations
We also need to set the relevant configurations on Netlify. This can be done by the website settings as well, but we can also use a netlify.toml file in the repo:
[build]
command = "yarn build"
functions = "out_functions"
publish = "out_publish"
They specify the command to build the site as well as the output directory, corresponding the the directory created by the next-on-netlify script.
Set target
to serverless
in Nextjs configurations
// next.config.js
module.exports = {
target: "serverless",
};