Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 7 min read

Next.js 16 on GitHub Pages: fixing missing CSS, broken images and export errors

A Next.js site on GitHub Pages usually breaks in one of two ways: the build stops with an error, or the build passes and the live page shows up with no styles and broken images. I started from a fresh create-next-app pr

A Next.js site on GitHub Pages usually breaks in one of two ways: the build stops with an error, or the build passes and the live page shows up with no styles and broken images.

I started from a fresh create-next-app project, exported it, and served the out folder under /ghp/ on a small local server, the same way a project site lives at username.github.io/repo-name/. Then I checked every page with Playwright. Below is each failure I hit, with the real output, and the config and workflow that fixed them.

Tested on Next.js 16.4.6, React 19.3.0, Tailwind CSS 4.3.3 and Node 22.23.5.

1. output: 'export' fails on a fresh project

In 16.4.6, create-next-app writes a next.config.ts with cacheComponents: true and partialPrefetching: true. Adding output: "export" to it stops the build:

> Build error occurred
Error: Invariant: PPR cannot be enabled in export mode

Removing only cacheComponents gives the next error:

Error: `partialPrefetching` requires `cacheComponents` to be enabled. Please update your next.config.ts accordingly.

Remove both lines. I covered why Cache Components and static export don't mix in 4 Next.js 16 traps that break static exports.

2. The page loads with no CSS or JavaScript

A project site is served from /repo-name/, but by default Next.js writes every asset URL from the domain root. Without basePath, this is what Playwright saw at /ghp/:

h1 color: rgb(0, 0, 0)
failed requests:
  404 /_next/static/chunks/3x6hs2kao5d3_.css
  404 /_next/static/chunks/1pcw6gskne7pf.js
  404 /_next/static/chunks/1wnov70f88xjy.js
  ...
  404 /next.svg
  404 /hero.png

The HTML arrives, but the stylesheet and scripts are requested from /_next/... instead of /ghp/_next/.... Setting basePath: "/ghp" fixes the CSS and JavaScript. The docs note that the value is inlined into the client bundles, so it has to be set at build time.

3. Images still 404 with basePath set

With basePath: "/ghp" the styles came back, but two images and one link were still broken:

img-string: /next.svg -> BROKEN
img-import: /ghp/_next/static/media/window.2y2m02cqmmj5t.svg -> loaded
img-png: /hero.png -> BROKEN
link-next: /ghp/about
link-plain: /about

What gets the prefix automatically:

  • next/link hrefs
  • statically imported images (import icon from "@/public/window.svg")
  • the app/favicon.ico file convention (<link rel="icon" href="/ghp/favicon.ico?...">)

What doesn't:

  • next/image with a string src such as "/hero.png". The basePath docs say you have to add the prefix yourself.
  • plain <a href="/about"> tags

A small helper keeps that in one place:

// lib/asset.ts
// Prefix files from /public with the basePath set at build time.
export function asset(path: string) {
  return `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${path}`;
}
// app/page.tsx
import Image from "next/image";
import Link from "next/link";
import windowIcon from "@/public/window.svg";
import { asset } from "@/lib/asset";

export default function Home() {
  return (
    <main className="p-8">
      <h1 className="text-3xl font-bold text-emerald-600">Hello from GitHub Pages</h1>
      <Image src={asset("/next.svg")} alt="Next.js logo" width={100} height={20} />
      <Image src={windowIcon} alt="Window icon" />
      <Image src={asset("/hero.png")} alt="Hero" width={800} height={400} />
      <Link href="/about">About (next/link)</Link>
      <a href={asset("/about/")}>About (plain a)</a>
    </main>
  );
}

The NEXT_PUBLIC_ prefix matters. Next.js inlines those variables into the browser bundle at build time, so the same value works in Server and Client Components.

4. The build passes, but PNGs point to /_next/image

This one has no error at all. Without images: { unoptimized: true }, next build exited with code 0 and wrote this for a PNG:

<img alt="Hero" ... src="/_next/image?url=%2Fhero.png&amp;w=1920&amp;q=75"/>

/_next/image is the image optimization server, and GitHub Pages doesn't have one, so the image breaks in production. The SVGs from the starter didn't show it, because Next.js serves any src ending in .svg without optimization. It only appeared once I added a PNG.

next dev does catch it. The page returned a 500 with:

β¨― Error: Image Optimization using the default loader is not compatible with `{ output: 'export' }`.
  Possible solutions:
    - Remove `{ output: 'export' }` and run "next start" to run server mode including the Image Optimization API.
    - Configure `{ images: { unoptimized: true } }` in `next.config.js` to disable the Image Optimization API.

In 16.4.6 the check that throws this error only runs when NODE_ENV isn't production, so next build never shows it. Use images: { unoptimized: true }, or a custom loader as described in the static exports guide.

5. Refreshing /about returns 404

Without trailingSlash, the export writes about.html. Client-side navigation worked, but a reload on my test server, which only serves real files and folder index.html files, did not:

200 fetch /ghp/about.txt?_rsc=Kj5MPPJ2XCusE5Hx
url http://localhost:4002/ghp/about About
--- reload
404 document /ghp/about

Whether /about resolves to about.html depends on the host. With trailingSlash: true, the export writes about/index.html instead, so a direct load doesn't depend on rewrite rules:

direct load /about/: 200 About

6. The config that works

// next.config.ts
import type { NextConfig } from "next";

const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";

const nextConfig: NextConfig = {
  output: "export",
  basePath,
  trailingSlash: true,
  images: { unoptimized: true },
  // Generated by create-next-app 16.4: this is what loads Tailwind CSS.
  turbopack: {
    rules: {
      "*.css": {
        loaders: ["@tailwindcss/turbopack"],
        as: "*.css",
      },
    },
  },
};

export default nextConfig;

Locally, NEXT_PUBLIC_BASE_PATH is unset, so next dev still runs at localhost:3000/ (I checked: / and /about/ both returned 200). In CI, the workflow sets it.

7. Don't let configure-pages write your Next.js config

GitHub's starter workflow for Next.js passes static_site_generator: next to actions/configure-pages, which injects basePath into your config file. In the v6 source, it only looks for next.config.js, .cjs or .mjs. With only a next.config.ts, it creates a new next.config.js holding just output, basePath and images.unoptimized.

Next.js 16.4.6 checks for next.config.js before next.config.ts. I didn't run the action itself. I recreated the file its source writes, next to my next.config.ts, and built:

βœ“ Running next.config.js took 43ms
...
Warning: Parsing CSS source code failed
> 8 | @theme inline {
Unknown at rule: @theme

The build still exited with code 0, but the Turbopack rule that loads Tailwind was gone. So were the Tailwind classes and trailingSlash. Leave out static_site_generator and pass the action's base_path output as an environment variable instead. The Next.js team's deploy-github-pages template uses the same approach.

8. The workflow

In the repo, go to Settings β†’ Pages β†’ Source and pick GitHub Actions. Then add .github/workflows/deploy.yml:

name: Deploy to GitHub Pages

on:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 22
          cache: npm
      - id: pages
        uses: actions/configure-pages@v6
      - run: npm ci
      - run: npx next build
        env:
          NEXT_PUBLIC_BASE_PATH: ${{ steps.pages.outputs.base_path }}
      - uses: actions/upload-pages-artifact@v5
        with:
          path: ./out

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - id: deployment
        uses: actions/deploy-pages@v5

base_path is "/repo-name" for a project site and "" for a user site or a custom domain, so the same workflow covers all three. actionlint 1.7.12 reports no errors for this file. I couldn't run it on GitHub from my test sandbox, so check the first run in the Actions tab.

About .nojekyll: you only need it if you publish out from a branch. In that case Jekyll skips folders that start with _, and that includes _next. With the workflow above there is no Jekyll step, because the action uploads out as it is. Also, upload-pages-artifact leaves out dotfiles unless you set include-hidden-files: true.

9. Test the sub-path before you push

You can preview the real URL structure without deploying:

NEXT_PUBLIC_BASE_PATH=/ghp npx next build
rm -rf preview && mkdir preview && cp -r out preview/ghp
python3 -m http.server 4005 -d preview

Open http://localhost:4005/ghp/ and look for 404s in the Network tab. With the config above, my Playwright check reported:

Next.js logo: /ghp/next.svg -> loaded
Window icon: /ghp/_next/static/media/window.2y2m02cqmmj5t.svg -> loaded
Hero: /ghp/hero.png -> loaded
after About (next/link): /ghp/about/ | h1: About
after About (plain a): /ghp/about/ | h1: About
direct load /about/: 200
failed requests: none

The export also writes out/404.html, the file name GitHub Pages uses for a custom 404 page. Every asset URL in it carries the basePath, so it keeps its styles at any depth. On my test server, /ghp/blog/missing/post/ returned a 404 status and the page's CSS loaded from /ghp/_next/static/....

Wrapping up

The short version for a Next.js 16 project site on GitHub Pages:

  1. Remove cacheComponents and partialPrefetching from the generated config.
  2. Set basePath from NEXT_PUBLIC_BASE_PATH, and prefix string image paths and plain links.
  3. Turn on images.unoptimized, even if the build doesn't complain.
  4. Use trailingSlash: true.
  5. Pass base_path from configure-pages instead of letting it rewrite your config.

Are you hosting a Next.js site on GitHub Pages, or did you move to another static host? What broke first for you?

If you use Claude Code, Cursor or Codex, the free MIT edition of my Next.js Launch Skills includes a pre-launch checklist with a link crawler: npx skills add nandot12/nextjs-launch-skills (GitHub).

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.