
Deploying a Next.js application with zero downtime is crucial, especially in production environments where any delay can affect user experience. In this article, we’ll walk you through setting up a deployment process that minimizes downtime and ensures a smooth transition between builds.
When deploying updates to your Next.js application, there’s always a risk of downtime—especially on a VPS where resources might be more limited compared to cloud platforms. Downtime can occur for various reasons:
next.config.jsTo start, you’ll need to configure your next.config.js file to support a custom build directory. This allows us to build the project in a temporary location before swapping it with the existing build directory. Add the following line to your next.config.js:
module.exports = {
distDir: process.env.BUILD_DIR || '.next',
};This configuration ensures that during the build process, the output will be placed in the directory specified by the BUILD_DIR environment variable, or .next by default.
deploy.sh ScriptNext, you’ll create a deployment script, deploy.sh, that automates the process of pulling the latest code, installing dependencies, building the project, and handling the deployment. Here’s the script:
#!/bin/bash
echo "Deploy starting..."
git pull
npm install || exit
BUILD_DIR=temp npm run build || exit
if [ ! -d "temp" ]; then
echo '\033[31m temp Directory not exists!\033[0m'
exit 1;
fi
if [ -d ".next" ]; then
mv .next .next_backup || exit
fi
rm -rf .next || {
echo '\033[31m Failed to remove old .next directory!\033[0m'
mv .next_backup .next
exit 1;
}
mv temp .next || {
echo '\033[31m Failed to move new build to .next!\033[0m'
mv .next_backup .next
exit 1;
}
pm2 reload nextapp --update-env || {
echo '\033[31m PM2 reload failed! Reverting to old build...\033[0m'
mv .next_backup .next
exit 1;
}
rm -rf .next_backup
echo "Deploy done."After setting up the script, follow these steps to deploy your Next.js application with zero downtime:
First, log in to your VPS using SSH. This will give you access to the server where your Next.js application is hosted.
ssh your-username@your-vps-ipnext.config.js as described in the previous section.deploy.sh script and make sure it’s executable:chmod +x deploy.shWhenever you need to update your application, simply run the deployment script:
sh deploy.shThe script will pull the latest code, install dependencies, build the project, and reload the application with zero downtime.
By following this deployment process, you can ensure that your Next.js application experiences zero downtime during deployments. The script handles potential errors and provides a fallback mechanism to keep your application running smoothly. Whether you’re deploying updates or scaling your application, this approach will help you maintain a seamless user experience.