To prepare a Next.js app for deployment, you need to create a custom Next.js server (server.js), modify the package.json file, and build the app.
- Create a custom Next.js server (server.js)
Create a server.js file in the root directory, you can check the Next.js guide for what’s needed. Add this code to the file:
- Modify the package.json file
Modify the package.json file to set the environment to production on the start script and run the server.js file you created in the project root directory. Here you’ve replaced the default Next start server script with our own custom server.
{ "scripts": { "start": "NODE_ENV=production node server.js", } }
Make sure you install the required dependencies by running npm install in your terminal.
- Build a Next.js application
To build a Next.js application:
Open your terminal and navigate to your project directory. Run the build command:
npm run build
Ensure that there are no errors during the build process. If there are, they need to be fixed before going on.
- Prepare Files for Deployment
Open the file manager and locate your Next.js project files. Enable visibility for any hidden files. Exclude the following folders/files:
node_modules; .git; README.md; .gitignore. Select all remaining files and folders. Create a ZIP archive of the selected files:
It's important to exclude the node_modules directory because it’s often large and not needed for deployment. The necessary modules will be installed on the server at a later stage.
- Upload the archive file to your cPanel on shared hosting.