I am creating a blogging application using NextJS and React. I already undernstand the basics because of this tutorial
So I tried to implement the blogging application. When I try to test it in development mode yarn dev the routing are fine. But if I build it yarn build and export into static HTML yarn export. The routing misses up when I click on the link it goes on the right page but when I refresh the browser it always takes me back to the / page.
Why is this happening?
Here is the Sample Code
Header.js Component
import Link from 'next/link'
const linkStyle = {
marginRight: 15
}
export default function Header() {
return (
<div>
<Link href="/">
<a style={linkStyle}>Home</a>
</Link>
<Link href="/about">
<a style={linkStyle}>About</a>
</Link>
</div>
)
}
MyLayout.js Component
import Header from './Header'
const layoutStyle = {
margin: 20,
padding: 20,
border: '1px solid #DDD'
}
export default function Layout(props) {
return (
<div style={layoutStyle}>
<Header />
{props.children}
</div>
)
}
index.js
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
function getPosts() {
return [
{ id: 'hello-nextjs', title: 'Hello Next.js' },
{ id: 'learn-nextjs', title: 'Learn Next.js is awesome' },
{ id: 'deploy-nextjs', title: 'Deploy apps with ZEIT' }
]
}
const PostLink = ({ post }) => (
<li>
<Link href="/p/[id]" as={`/p/${post.id}`}>
<a>{post.title}</a>
</Link>
<style jsx>{`
li {
list-style: none;
margin: 5px 0;
}
a {
text-decoration: none;
color: blue;
font-family: 'Arial';
}
a:hover {
opacity: 0.6;
}
`}</style>
</li>
)
export default function Blog() {
return (
<Layout>
<h1>My Blog</h1>
<ul>
{getPosts().map(post => (
<PostLink key={post.id} post={post} />
))}
</ul>
</Layout>
)
}
package.json
{
"name": "hello-next",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start -p $PORT",
"export": "next export"
},
"license": "ISC",
"dependencies": {
"next": "latest",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-markdown": "^4.0.6"
}
}
EDIT: I followed this guide nextjs.org/learn/basics/deploying-a-nextjs-app. But I use "Deploying to Your Own Environment" steps.So basically the same structure as this repo github.com/zeit/next-learn-demo/tree/master/8-deploying
I solved this by adding the following to next.config.js:
module.exports = {
exportTrailingSlash: true,
}
https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash
I guess this depends on your web server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With