This is an example of a gh-page built with Next.js.
The original project is from A statically generated blog example. My intention is to build my own blog with Next.js, and deploy it both on Vercel and GitHub Pages.
npm run dev //development mode
npm run start //production mode
issue: The production mode needs some config mentioned below.
-
Create a github repository.
-
Set the remote origin to github repository.
-
Open
next.config.js
to configure your own urls.const prod = process.env.NODE_ENV === "production"; const basePath = "/deploy-nextjs-to-github-pages"; // set with "" if the application is deployed directly under the domain with no sub-path module.exports = prod ? { basePath: basePath, images: { loader: 'imgix', path: `https://imagicbell.github.io${basePath}`, //if images are hosted on other CDNs instead of public folder, please change the root path }, env: { basePath: basePath } } : { env: { basePath: '' } };
-
const basePath: if your github repository's name is [github-user-name].github.io, then just set
const basePath = ""
. Or replace/deploy-nextjs-to-github-pages
with your/[github-repository-name]
. Because Github Pages deploy the repository named with [github-user-name].github.io directly under the domain.If
basePath
is given a sub-path, when you runnpm run start
, you should open http://localhost:3000/[github-repository-name] to see the result, or you will see 404 error. -
images:
next export
doesn't support thenext/image
component's default loader, see this. So we need to configure other loader.If your images are hosted on other CDNs, not under
public
directory, then you should set theimages.path
with the corresponding CDN link. -
env: This enviroment variables is used somewhere in code, mainly for dealing with the sub-path issue.
-
-
Run the following command.
npm run deploy
-
Change github repository Settings. Navigate to GitHub Pages, set the Source to be branch "gh-pages", directory /(root), and click Save.
-
Wait from a while and click your gh-page link to test the result!
-
404 error
This is related to the
basePath
configured innext.config.js
. If it is given a customized path, then all the routes come after [domain]/[basePath]/.GitHub Pages give a default link https://[github-user-name].github.io/ if the repository is named with "[github-user-name].github.io". But if you name another, then the Github Pages will publish the content at https://[github-user-name].github.io/[github-repository-name].
-
Image failed to load
If you use
Image
component fromnext/image
to load image, then everything is ok.But if you use html
img
tag, there are 2 work-around ways:-
Set the
src
ofimg
tag as:<img src={`${process.env.basePath}${relative-path-of-image-source}`} />
where
process.env.basePath
is defined innext.config.js
, see here. -
Move the image assets to the sub-path. If the images are under
public
directory, then create a sub-directory named with thebasePath
and move the images under this directory.
-