Buy All 40 Premium WordPress Themes for $54.99

How to Host a Next.JS App on GitHub Pages

How to Host a Next.JS App on GitHub Pages

Next.js is React Framework created by Vercel. The recommended way to host a next.js app is directly on Vercel. But if you need to host a Next.JS app on GitHub pages it will require a few additional steps. Here is a full guide:

  1. Create a GitHub repository. Clone the repository locally (on your computer) and add your Next.js react app files.
  2. Open command prompt (or terminal) and navigate to your react app folder. Then execute the following command:
npm install gh-pages --save-dev

3. At the root folder of your Next.JS app, create a file with name = replacer.js with the following content:

const replace = require("replace-in-file");
const options = {
  //you may need to modify the file address to suite your project
  files: "./build/index.html",
  from: [/src="\//g, /href="\//g],
  to: ['src="./', 'href="./'],
};
(async function () {
  try {
    const results = await replace(options);
    console.log("Replacement results:", results);
  } catch (error) {
    console.error("Error occurred:", error);
  }
})();

4. Update the next.config.js content with the following values:

module.exports = {
  env: {
    PUBLIC_URL: "https://your-organization-or-username.github.io/my-nextjs-app",
    assetPrefix: './'
  }
};

5. Open package.json file for edit and apply the following changes:

At the beginning, insert the following:

"homepage": "https://your-organization-or-username.github.io/my-nextjs-app"

and in scripts, add following lines:

"scripts": {
    ...
    "replaceFilePaths": "node replacer.js",
    "dev": "next dev",
    "build": "next build && next export -o build && npm run replaceFilePaths",
    "start": "next start",
    "export": "next export -o build && npm run replaceFilePaths",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  }

6. Execute the following command:

npm run deploy

Note: It will create a new branch (gh-pages) with build files (HTML, JavaScript, and CSS) for the hosting

7. In GitHub repo -> branch gh-pages -> _next folder, add an empty file with filename:

.nojekyll

5. (Optional) commit and push your changes to main branch

And that’s all. Now your Next.JS app is online. You can open your GitHub repo in browser, Settings -> Pages to see more details, add a custom domain, etc.)

Leave a Reply