How To Deploy Next JS App to Github Pages

How To Deploy Next JS App to Github Pages

How To Deploy Next JS App to Github Pages

Deploying your Next.js app to GitHub Pages can be a great way to showcase your projects, portfolio, or even host small applications for free. GitHub Pages provides a fast, reliable, and cost-effective solution for serving static websites directly from your repository. However, because Next.js is primarily a React framework built for hybrid rendering (SSR and SSG), deploying it to GitHub Pages requires a few extra steps and configurations.

In this in-depth guide, we'll walk you through every step of deploying a Next.js app to GitHub Pages --- from configuring your project and GitHub repository to building and deploying your static export. We'll also explore some common pitfalls, troubleshooting tips, and best practices.

By the end, you'll be able to confidently deploy your Next.js app to GitHub Pages and keep it updated with ease.

🧭 Understanding GitHub Pages and Next.js Compatibility

Before jumping into the process, it's important to understand how Next.js and GitHub Pages work differently.

  • Next.js can render content both on the server (SSR) and at build time (SSG).\
  • GitHub Pages, on the other hand, only supports static sites --- it can serve HTML, CSS, and JavaScript files but not Node.js or server-side code.

This means you can only deploy static exports of your Next.js app (not SSR-based features) on GitHub Pages.

If your app relies heavily on APIs or server-side rendering, GitHub Pages won't be suitable. But for portfolios, blogs, documentation, or marketing sites, GitHub Pages is a great fit.

βš™οΈ Step 1: Setting Up Your Next.js Project

If you don't already have a Next.js app, create one using the following command:

npx create-next-app my-next-app
cd my-next-app

This will generate a fresh project with a basic structure.

If you already have a project, ensure that it's working locally:

npm run dev

Visit http://localhost:3000 to confirm that your app runs correctly.

🧩 Step 2: Configuring next.config.js for Static Export

Since GitHub Pages doesn't support server-side rendering, you'll need to export your app as static files.

Open your next.config.js file and modify it as follows:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  basePath: '/my-next-app',
  images: {
    unoptimized: true,
  },
}

module.exports = nextConfig

Explanation:

  • output: 'export' tells Next.js to generate a static export.\
  • basePath defines the subdirectory under your GitHub Pages URL (must match your repository name).\
  • images.unoptimized disables the default Next.js Image Optimization feature, which requires a server.

πŸ’‘ If your repository name is portfolio, set basePath to /portfolio.

πŸš€ Step 3: Update the scripts in package.json

To make deployment easier, update your package.json scripts section to include a deploy command.

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "export": "next export",
  "deploy": "next build && next export && gh-pages -d out"
}

Here's what happens:

  • next build builds your Next.js app.\
  • next export exports it to static HTML files in the /out directory.\
  • gh-pages -d out publishes those static files to your GitHub Pages branch.

πŸ› οΈ Step 4: Install gh-pages Package

The gh-pages package automates the process of deploying your static files to GitHub Pages.

Install it by running:

npm install gh-pages --save-dev

This will add it as a development dependency to your project.

πŸ—‚οΈ Step 5: Configure Your GitHub Repository

  1. Go to GitHub and create a new repository.
    Name it exactly as your project (for example, my-next-app).
  2. Initialize Git in your project if not already done:
git init
git remote add origin https://github.com/yourusername/my-next-app.git
git add .
git commit -m "Initial commit"
git push -u origin main

Now your local code is connected to your remote repository.

🌐 Step 6: Deploy Your App

Once your code is pushed, you can deploy the static site by running:

npm run deploy

This command will:

  • Build and export your project into the /out folder.
  • Push the contents of that folder to the gh-pages branch of your repository.

After the process completes successfully, go to your repository β†’ Settings β†’ Pages.

  • Under Source, select Deploy from branch.\
  • Choose the gh-pages branch and the / (root) directory.\
  • Click Save.

GitHub will deploy your static site automatically within a few minutes.

Your app should now be live at:

https://yourusername.github.io/my-next-app/

⚑ Step 7: Test the Deployment

Open your GitHub Pages URL in a browser and check if your app is working correctly.

If you see blank pages or 404 errors, make sure:

  • The basePath in next.config.js matches your repository name.
  • You've correctly set the branch to gh-pages in GitHub Pages settings.
  • The /out directory exists and contains your exported files.

You can rebuild and redeploy anytime by running:

npm run deploy

🧠 Step 8: Custom Domain (Optional)

If you have a custom domain, you can connect it to your GitHub Pages deployment.

  1. Go to your repository β†’ Settings β†’ Pages.
  2. Under Custom Domain, enter your domain name.
  3. Add the following DNS record in your domain provider:
<!-- -->
Type: CNAME
Name: www
Value: yourusername.github.io

Next.js will automatically include your custom domain in the build process.

πŸ”§ Troubleshooting Common Issues

Deploying to GitHub Pages can sometimes cause unexpected issues. Here are some common ones and how to fix them.

❌ Problem: Images Not Loading

Solution: Add the following line to your next.config.js:

images: {
  unoptimized: true
}

This disables Next.js's built-in image optimization that requires a server.

❌ Problem: CSS or JS Not Found

Solution: Ensure you've correctly set your basePath and assetPrefix in the configuration file:

const nextConfig = {
  output: 'export',
  basePath: '/my-next-app',
  assetPrefix: '/my-next-app/',
}

This ensures that all static assets are loaded from the correct relative path.

❌ Problem: 404 on Page Refresh

Solution: Since GitHub Pages doesn't support client-side routing natively, add a 404.html redirect workaround.

Copy your index.html file to 404.html in the /out folder after the export process.

cp out/index.html out/404.html

This ensures users are redirected back to your home page when refreshing or visiting non-root routes.

❌ Problem: Deployment Fails

If your deployment fails with permission or branch errors:

  • Check if you have permissions to push to the repository.\
  • Run git remote -v to confirm the correct remote URL.\
  • Try deleting the gh-pages branch and redeploying.

🧩 Step 9: Automating Deployment with GitHub Actions

If you prefer a CI/CD pipeline, you can automate deployment using GitHub Actions.

Create a new file: .github/workflows/deploy.yml

name: Deploy Next.js to GitHub Pages

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Install dependencies
        run: npm install

      - name: Build and Export
        run: npm run build && npm run export

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./out

Now, every time you push to main, GitHub will automatically build and deploy your app to GitHub Pages.

πŸ“¦ Step 10: Keeping Your Deployment Updated

Each time you make changes to your app, follow these steps:

  1. Commit your changes:

    git add .
    git commit -m "Updated content"
    git push origin main
    
  2. Deploy again using:

    npm run deploy
    

Or if you've set up GitHub Actions, it will deploy automatically upon pushing to the main branch.

πŸ’‘ Best Practices for Deploying Next.js to GitHub Pages

Here are some key tips to keep in mind:

  • Use static generation (SSG) whenever possible.
  • Avoid using server-side rendering (SSR) or API routes.
  • Optimize images manually since GitHub Pages doesn't handle Next.js optimization.
  • Keep your repository clean --- exclude the .next and node_modules folders from commits.
  • Test locally before deploying to prevent broken builds.

🧱 Real-World Example

Let's say you're building a personal portfolio website using Next.js. You name your project my-portfolio and want to host it on GitHub Pages.

You would:

  1. Add this in next.config.js:

    const nextConfig = {
      output: 'export',
      basePath: '/my-portfolio',
      assetPrefix: '/my-portfolio/',
      images: { unoptimized: true }
    }
    module.exports = nextConfig
    
  2. Push the project to a repository named my-portfolio.

  3. Install gh-pages and deploy it using npm run deploy.

  4. Access it at https://yourusername.github.io/my-portfolio.

That's all it takes to make your Next.js portfolio live on GitHub Pages!

🏁 Conclusion

Deploying a Next.js app to GitHub Pages is a straightforward process once you understand the limitations and setup requirements. It's perfect for static sites, portfolios, or documentation projects.

To summarize:

  • Use output: 'export' in next.config.js.
  • Set your basePath and assetPrefix properly.
  • Use gh-pages for quick deployments or GitHub Actions for automation.

With this setup, you can deploy and maintain your Next.js projects on GitHub Pages with minimal effort.

If you're working on professional Next.js or MERN stack projects and want expert support for deployment, scalability, and performance optimization, consider hiring AAMAX --- a full-service digital marketing company offering Web Development, Digital Marketing, and SEO Services. Their experienced development team can help you create and deploy robust, high-performing applications tailored to your business needs.

With the right setup and expert guidance, your Next.js app can shine on GitHub Pages and beyond!

Related Blogs

How To Deploy React JS Application

How To Deploy React JS Application

React JS apps are static single-page applications (SPAs), which means they can be hosted almost anywhere that serves static files. Let’s look at some ...

How To Get Params in Next JS

How To Get Params in Next JS

With this knowledge, you're now equipped to handle any URL structure in your Next.js applications --- from simple slugs to complex query strings --- l...

How To Deploy Next JS App to Github Pages

How To Deploy Next JS App to Github Pages

In this in-depth guide, we'll walk you through every step of deploying a Next.js app to GitHub Pages --- from configuring your project and GitHub repo...

How To Deploy Next JS App to Vercel

How To Deploy Next JS App to Vercel

From automatic builds and global CDN delivery to seamless environment variable management and continuous deployment β€” Vercel provides everything you n...

How To Deploy Next JS App to DigitalOcean

How To Deploy Next JS App to DigitalOcean

With the right setup and ongoing optimization, your Next.js app on DigitalOcean can deliver fast, secure, and reliable experiences for users worldwide...

How To Deploy Next JS App

How To Deploy Next JS App

Deploying a Next.js app doesn’t have to be complicated. Whether you choose Vercel for simplicity, VPS for flexibility, or Docker for scalability, the ...

Need Help? Chat with Our AI Support Bot