Dynamic Routes in Next.js 14

2024-03-16
By: O. Wolfson

Understanding Dynamic Routes:

Dynamic routes in Next.js allow developers to create pages with URLs that dynamically adapt to the content being served. This flexibility is achieved through the use of brackets ([ ]) in the route definition. For instance, a dynamic route like messages/[id] signifies that the page can be accessed with URLs such as messages/1, messages/2, etc., where 1, 2, etc., are dynamic parameters.

Creating a Dynamic Server Component: To illustrate dynamic routing in action, let's build a simple Next.js 14 server component that displays messages based on the provided message ID.

jsx
import React from "react";

function Message({ params }: { params: { id: string } }) {
  return (
    <div className="flex flex-col gap-8 w-full max-w-xl">
      <div>Message: {params.id} </div>
    </div>
  );
}

export default Message;

In the above code snippet, we define a functional component Message that receives params as a prop containing the dynamic parameter id. Within the component, we render a simple message displaying the provided id. In an actual app we would likely fetch the message from a database or an API, based on the id parameter, but for the sake of simplicity we'll just display the id in the browser.