In Next.js, you can use query parameters as rewrite variables to dynamically handle URLs, which is highly beneficial for building applications with clean URL structures. Here are the steps and examples to achieve this:
Step 1: Configure Rewrite Rules in next.config.js
First, configure rewrite rules in the project's next.config.js file. Rewriting enables you to map one URL path to another while maintaining a clean and user-friendly URL structure.
Suppose you have a blog application where you want the URL for a single blog post to be /post/123 instead of /post?slug=123. You can set up the rewrite rules as follows:
javascriptmodule.exports = { async rewrites() { return [ { source: '/post/:slug', destination: '/post?slug=:slug' // Map path parameters to query parameters } ] } }
Step 2: Retrieve Query Parameters in Page Components
After configuring the rewrite rules, you can access these query parameters in your page components using Next.js's useRouter hook. This enables you to render different content based on the URL parameters.
For example, if your page path is /pages/post.js, you can retrieve the query parameters as follows:
javascriptimport { useRouter } from 'next/router' function Post() { const router = useRouter() const { slug } = router.query // Access the slug parameter via destructuring return ( <div> <h1>Post: {slug}</h1> {/* Fetch and display the blog post based on the slug from an API */} </div> ) } export default Post
Practical Example
Suppose you run a movie database website where you want users to access movie details via clean URLs, such as /movie/the-dark-knight instead of /movie?title=the-dark-knight. You can set up the rewrite rules as described and retrieve the title parameter in the movie details page.
This configuration enhances URL readability and SEO-friendliness while making the page logic more transparent and manageable.
Summary
By configuring rewrite rules in next.config.js and correctly retrieving and using query parameters in page components, you can effectively leverage Next.js's routing capabilities to enhance application functionality and user experience. This approach is highly beneficial for building complex, highly customizable web applications.