Let's assume that you have the following folder structure in Next.js:
├── posts | ├── _data.js | ├── a.md | ├── b.md | ├── c.md ├── pages | ├── _app.js | ├── index.js | ├── [post].js
_data.js
contains the Markdown's files info:
javascriptvar posts = { 'a':{ 'title': `Title A`, 'date': [24, 'January', 2022] }, 'b':{ 'title': `Title B`, 'date': [23, 'January', 2022] }, 'c':{ 'title': `Title C`, 'date': [22, 'January', 2022] } }
To display the content of each post depending on the slug ([post]
):
javascriptimport posts from '../posts/_data' import fs from 'fs' import { join } from 'path' const postsDirectory = join(process.cwd(), 'posts') const Post = ({ post }) => { return post } export async function getStaticPaths() { const paths = Object.keys(posts).map(key => ({ params: { post: key} })) return { paths, fallback: false } } export async function getStaticProps({ params }) { const fullPath = join(postsDirectory, `${params.post}.md`) const fileContents = fs.readFileSync(fullPath, 'utf8') return { props: { post: fileContents } } } export default Post
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.