I just started using Next JS, following Brad Traversy's tutorial on youtube. I used next export
to export the program, just like he did in his tutorial. I used serve -s out -p 8000
. The page loads on localhost:8000
, however when I go to other links like localhost:8000/about
, it just reloads the home page.
I looked for solutions online, I tried adding "trailingSlash": true
to my next.config.js
file, and it still doesn't work.
And the most confusing part is when clicked on a Link element (from the "next/link" module) on the page, it works, and it takes me to the correct page. But when I want to access it directly from the address bar it doesn't work.
Btw it also works during production.
Edit
Here is the next.config.js
file:
module.exports = {
trailingSlash: true,
};
Here is the package.json
file:
{
"name": "next-cc",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"export": "next build && next export"
},
"dependencies": {
"next": "10.1.3",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}
Edit: Here is the folder structure
Here is a link to the project
The issue is not with Next.js or the export, but rather with the command you're running to serve the static files.
Using the -s
option in the serve
command will rewrite all files to index.html
. Simply run the command without that option.
npx serve out -p 8000
I experienced the same issue with a complete static site I wanted to export. Unfortunately the proposed answer did not work for me, because I was deploying the site to an apache instance.
Next export basically renders the site pages with html extensions, so next/link tags to your /about
page will still work when clicked, but not when called via your browser url.
To overcome this you need to make use of the exportPathMap
entry in your next.config.js
(exportPathMap in documentation)
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
'/about': { page: '/about' },
'/about/index': { page: '/about' },
}
},
Usually Next uses the pages directory and exports static files with the page name and appends .html to them - so http://localhost:3000/about becomes http://example.com/about.html - but if you still want the short urls you can add an /about/index
entry in your path map, which will generate an index.html
file in an about
directory, which will then still have your short /about
link working as expected on your live server, even on page reloads or by entering the url in browser directly.