Lesson 1: Dynamic Routing
Dynamic routing in Next.js allows you to create pages that adapt to different data inputs. This is achieved using square bracket syntax for dynamic segments in the pages/ directory. For example:
- File Structure:
- Accessing Dynamic Parameters: Use the useRouter hook or server-side methods like getStaticProps or getServerSideProps to retrieve dynamic values:
export default function Post() { const router = useRouter(); const { id } = router.query;
return
Post ID: {id}
;
}
Lesson 2: API Routes
API routes allow you to create serverless backend functionality directly within your Next.js application. These are created inside the pages/api/ directory. Example:
- File Structure:
- Sample API Route:
{ res.status(200).json({ message: ‘Hello, API!’ });
}
- Usage: Call the API route from the frontend using fetch :
.then((res) => res.json())
.then((data) => console.log(data));
Lesson 3: Catch-All and Nested Routes
Catch-all routes allow you to capture multiple dynamic segments in a single route. Use square brackets with an ellipsis (… ) for this purpose.
- File Structure:
- Accessing Parameters:
export default function Post() { const router = useRouter(); const { slug } = router.query;
return
Slug: {slug.join(‘/’)}
;
}
Nested routes allow you to structure files and directories for better organization:
- Example Structure:
blog/
index.js -> /blog [slug].js -> /blog/:slug
Additional Resources
Leave a Reply