So I want to export static HTM with blog and prefetched posts. Example in next section. The issue is, I have a list of blog posts, and next Link should prefetch page of the blog post, which is named [post].js, as exported with next build, but it prefetch exact url of each post /post-1.js, /post-2.js,/post-3.js, which doesn't exist, so I have console full of 404. Ok this is logical since href of Link is/post-1and not[post.js], but this should be optimized some way, or should I just disable prefetch in this case?
next.config.js
module.exports = {
exportPathMap: async function(defaultPathMap, { dev, dir, outDir }) {
const postsData = await require('isomorphic-unfetch')('https://jsonplaceholder.typicode.com/posts')
const posts = await postsData.json()
return {
'/': { page: '/' },
...posts.splice(0, 10).reduce((acc, post) => ({ ...acc,
[`/post-${post.id}`]: { page: '/[post]', query: { id: post.id } }
}), {})
}
},
webpack: config => {
config.node = { fs: 'empty' }
return config
}
}
pages/index.js
import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
const Home = ({ posts }) => (
<div>
<Head>
<title>Home</title>
</Head>
<h1>Posts</h1>
{posts.map(post =>
<Link href={`/post-${post.id}`} key={post.id}>
<a>{post.title}</a>
</Link>
)}
<style jsx>{`
a { display: block; margin-bottom: 0.25em; }
`}</style>
</div>
)
Home.getInitialProps = async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await data.json()
return { posts: posts.splice(0, 10) }
}
export default Home
pages/[post].js
import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
const Post = ({ post }) => (
<div>
<Head>
<title>Home</title>
</Head>
<Link href="/">
<a>Back to posts</a>
</Link>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
)
Post.getInitialProps = async ({ query: { id } }) => {
const data = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
const post = await data.json()
return { post }
}
export default Post
Your <Link> usage is incorrect (<Link href={`/post-${post.id}`} key={post.id}>).
Please read the documentation about dynamic routing: https://github.com/zeit/next.js#dynamic-routing
<Link href="/post/[pid]" as="/post/abc"> <a>First Post</a> </Link>
Most helpful comment
Your
<Link>usage is incorrect (<Link href={`/post-${post.id}`} key={post.id}>).Please read the documentation about dynamic routing: https://github.com/zeit/next.js#dynamic-routing