I am creating a static blog using NextJS. I have used fs
and gray-matter
package to get the contents of markdown files.
Directory structure is like –
my-blog
-app
-[slug]
-page.js
-contents
-blogpost1
-index.md
-cover.png
-blogpost2
-index.md
-cover.png
[slug]/page.js
<main>
<h1>Title goes here</h1>
<img src={`/contents/${post.data.slug}/cover.png`}/>
<div>Content goes here</div>
</main>
I am unable to get the cover images using localhost/contents/blogpost1/cover.png
.
I am new to nextjs, what I am supposed to do?
2
Answers
In Next.js, static assets like images should be positioned in the public folder at the root of your project. To resolve the issue and exhibit the cover image for your blog posts, follow these steps:
Transfer the cover.png images to the public directory. Establish a new folder named covers inside the public directory and put the cover.png images there. The folder structure should resemble this:
In your blog post page component (page.js), update the image source to utilize the accurate path relative to the public directory:
Here, we’re assuming that the post.data.slug corresponds to the file name of the markdown file, which should match the name of the cover image file.
By situating the images in the public directory, Next.js will automatically serve them as static assets, and you can reference them using a relative path from the root of your project.
Ensure to restart the Next.js development server after implementing these changes. Now, when you visit localhost:3000, the cover image should be displayed correctly based on the respective blog post’s slug.
static assets in next.js served from public folder and this folder cannot be updated. once you build the app, only the images during the build time will be served. you have two options.
1- once you write the post, place the correct image in the public directory with
dynamicSlug.png
. So in your dynamic route, you can get that image with2- you set the metadata in markdown like this.
you use a cover image from external website. you need to configure
next.config.js
if you successfully parse the post markdown, you will have access to
post.coverImage
so you can use it