Alright, let’s roll up our sleeves and build a super simple blog using Next.js 15 dynamic routing! I’ll keep it chill and easy to follow.
Step 1: Set Up Your Next.js Project
If you haven’t already, create a new Next.js project:
npx create-next-app@latest my-blog
cd my-blog
Step 2: Create the Blog Folder Structure
Inside the app
folder, create a blog
folder, and inside that, create a [slug]
folder. Your structure should look like this:
app/
blog/
[slug]/
page.js
Step 3: Add Some Fake Blog Data
Let’s pretend we have a list of blog posts. Create a data.js
file in the root of your project to store some fake blog data:
// data.js
export const posts = [
{
slug: "my-first-post",
title: "My First Post",
content: "This is the content of my first post.",
},
{
slug: "another-post",
title: "Another Post",
content: "Here's another post.",
},
{
slug: "nextjs-is-awesome",
title: "Next.js is Awesome",
content: "Dynamic routing in Next.js",
},
];
Step 4: Create the Dynamic Blog Page
Now, let’s make the page.js
file inside app/blog/[slug]
. This is where the magic happens!
// app/blog/[slug]/page.js
import { posts } from "../../../data";
export default function BlogPost({ params }) {
const { slug } = params;
// Find the post that matches the slug
const post = posts.find((post) => post.slug === slug);
// If the post doesn't exist, show a 404 message
if (!post) {
return <h1>Post not found.</h1>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
Step 5: Create a List of Blog Posts
Let’s make a homepage that lists all the blog posts. Create a page.js
file in the app/blog
folder:
// app/blog/page.js
import Link from "next/link";
import { posts } from "../../data";
export default function Blog() {
return (
<div>
<h1>My Blog</h1>
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
</div>
);
}
Step 6: Run Your Blog
Fire up your dev server:
npm run dev
Now, visit http://localhost:3000/blog
. You’ll see a list of blog posts. Click on any post, and it’ll take you to the dynamic page for that post
Recap of What We Did:
- Created a dynamic route with
[slug]
. - Used fake data to simulate blog posts.
- Made a homepage listing all posts.
- Linked to individual posts using
next/link
.
And that’s it! This is all you gotta do to implement Dynamic Routing
Top comments (0)