How to Deploy a Static Next.js Site to GitHub Pages with GitHub Actions
🚀 How to Deploy a Next.js Site to GitHub Pages
Hello! Today I'm going to document the exact process I followed to deploy this blog to GitHub Pages. It's a fantastic way to host a static site (like a portfolio, blog, or documentation) completely for free, with the power of automated deployments using GitHub Actions.
This guide will walk you through every necessary configuration, from preparing your Next.js project to creating the deployment workflow.
🤔 Why Use GitHub Pages?
- It's Free: Perfect for personal projects and blogs.
- Simple: It integrates directly with your repository.
- Automated: With GitHub Actions, every
push
to yourmain
branch can automatically trigger a new deployment.
🛠️ Step 1: Configure Your Next.js Project for Static Export
GitHub Pages only serves static files (HTML, CSS, JS). Therefore, we need to tell Next.js to export our project as a static site instead of running a Node.js server.
Open your next.config.mjs
file and add the output: 'export'
option.
After this change, when you run npm run build
, Next.js will create an out
folder containing all the static files for your site, ready to be deployed.
🤖 Step 2: Create the GitHub Actions Workflow
This is the magic part. We will create a file that tells GitHub what to do every time we push code.
- In the root of your project, create the following folder structure:
.github/workflows/
. - Inside
workflows
, create a new file nameddeploy.yml
. - Paste the following code into
deploy.yml
:
This workflow does two things:
build
: Clones your code, installs dependencies, and builds the static site (npm run build
). Then, it uploads the resultingout
folder as an "artifact".deploy
: Takes the artifact from thebuild
job and deploys it to GitHub Pages.
⚙️ Step 3: Configure Your Repository for GitHub Pages
The final step is to tell your GitHub repository to serve its Pages site from the files deployed by our Action.
- Go to your repository on GitHub.
- Click on the Settings tab.
- In the left sidebar, click on Pages.
- Under "Build and deployment", in the "Source" dropdown, select GitHub Actions.
✅ Step 4: Commit, Push, and See the Magic!
Now, all you need to do is save all your changes and push them to the main
branch:
Go to the Actions tab in your GitHub repository. You will see your workflow running. Once it completes successfully (with green checkmarks), your site will be live at the URL provided in the Pages settings (e.g., https://your-user.github.io/your-repo/
).
🎉 Conclusion
And that's it! You now have a fully automated CI/CD pipeline to deploy your Next.js blog to GitHub Pages. Every time you write a new post and push it to main
, your site will update automatically. It's a powerful, professional, and completely free setup.
Happy coding! 👋