Dynamic Routes

Learn how to handle variable URLs (like products or user profiles) using JopiJS dynamic route segments.

Imagine you want to create a profile page for every user on your site. You can't manually create a folder for /user/alice, /user/bob, /user/charlie, and thousands of others.

The solution is Dynamic Routes. In JopiJS, you can make a folder name variable by wrapping it in brackets (e.g., [username]).

Prerequisites:


1. Creating a Dynamic User Profile

We will create a module dedicated to users and a dynamic page to display their profiles.

Step 1: Create the Module

Let's create a new module mod_users.

  1. Go to src/.
  2. Create a folder mod_users.
  3. Inside, create a folder @routes.

Step 2: Create the Dynamic Folder

  1. Inside @routes, create a folder named user.
  2. Inside user, create a folder named [username]. (With brackets!)

Path: src/mod_users/@routes/user/[username]/

Step 3: Create the Page

Inside [username], create page.tsx. JopiJS will automatically extract the value from the URL and pass it to your component via props.params.username.

Path: src/mod_users/@routes/user/[username]/page.tsx

import { JopiPageProps } from "jopijs/uikit";

export default function UserProfile(props: JopiPageProps) {
    // The variable name "username" comes from our folder name "[username]"
    const username = props.params.username; 
    
    return (
        <div className="p-10">
            <h1 className="text-2xl font-bold mb-2">User Profile</h1>
            <p className="text-lg">
                Hello, <span className="text-blue-600 font-bold">{username}</span>!
            </p>
        </div>
    );
}

Step 4: Verify

Open your browser and try different values:

  • http://localhost:3000/user/bob
  • http://localhost:3000/user/alice

The page adapts automatically to whatever you type!


2. Multiple Dynamic Segments

You can chain dynamic folders to manage hierarchical data, like reports organized by date: /reports/2024/05.

Step 1: Create the structure

  1. In mod_users/@routes, create a folder reports.
  2. Inside, create a folder [year].
  3. Inside [year], create a folder [month].
  4. Add a page.tsx inside [month].

Path: src/mod_users/@routes/reports/[year]/[month]/page.tsx

Step 2: The Code

import { JopiPageProps } from "jopijs/uikit";

export default function ReportPage(props: JopiPageProps) {
    // We get both parameters
    const { year, month } = props.params;

    return (
        <div className="p-10 border-l-4 border-purple-500 m-10 bg-purple-50">
            <h1 className="text-xl font-bold text-purple-900">Monthly Report</h1>
            <p className="text-purple-700">
                Viewing data for: <strong>{month} / {year}</strong>
            </p>
        </div>
    );
}

Check: Go to http://localhost:3000/reports/2024/12.