6 steps to deploy your React Next.js app with Github pages

October 11, 2024 (1mo ago)

Read on Dev.to →

Deploying a Next.js app to GitHub Pages can be a bit tricky due to the static nature of GitHub Pages and the dynamic features of Next.js. In this article, I'll walk you through the steps to successfully deploy do it.

Prerequisites

Step 1: Install gh-pages

npm install gh-pages --save-dev

Step 2: Update next.config.mjs

Next, you need to update your next.config.js (or next.config.mjs) file to handle the base path and asset prefix correctly.

const isProd = process.env.NODE_ENV === 'production';
const nextConfig = {
  reactStrictMode: true,
  images: {
    unoptimized: true, // Disable default image optimization
  },
  assetPrefix: isProd ? '/your-repository-name/' : '',
  basePath: isProd ? '/your-repository-name' : '',
  output: 'export'
};
 
export default nextConfig;

isProd checks if the NODE_ENV environment variable is set to 'production'. If it is, isProd will be true; otherwise, it will be false. Conditional assetPrefix and basePath are set to your repository name only if isProd is true. Otherwise, they are set to an empty string for local development. The images.unoptimized option is set to true to disable the default image optimization, which is not compatible with static exports.

Step 3: Update package.json

Update your package.json to include the homepage field and the deploy scripts.

"homepage": "https://<your-github-username>.github.io/<your-repo-name>",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d out"
  },

Replace and with your GitHub username and repository name.

Step 4: Deploy Your App

Run npm run predeploy and npm run deploy

These commands will:

Step 5: Configure GitHub Pages

Go to your repository on GitHub. Navigate to Settings > Pages. Under Source, select the gh-pages branch. Save the settings. Add manually the .nojekyll file at the root of the gh-pages branch on GitHub. Learn more about this here.

Step 6: Verify Deployment

After deploying, open your GitHub Pages URL (e.g., https://.github.io/) to verify that your app is live.

And voila!

Feel free to leave any questions or comments below. Happy coding!

Comments (3)

Add Comment
Abou Kone
Abou Kone@devakoneOctober 20, 2024 (1mo ago)

This is handy! I have the need to do just that! Thanks Dave!

MEtooHARD
MEtooHARD@metoohard_69c220aec4653ddNovember 10, 2024 (2w ago)

This helps!
struggled for deploying it to github pages
and this works!

David
David@daviidyNovember 12, 2024 (2w ago)

Glad to know it works. 🙂