How to Set Up Routing in react-server
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
A summary of how to set up routing in the react-server framework.
How to Configure Routing
File-Based Routing
File-based routing is a method where routing is determined by the directory structure and file names.
Previously, this was often referred to as Dynamic routing, but now it seems to be commonly called file-system routing.
react-server.config.mjs
Create this file in the root directory:
export default {
root: "pages",
}pages/index.jsx
export default function App() {
return <h1>Hello World</h1>
}Local Server Command
npx react-serverIf you can access and view the page at http://localhost:3000, then everything is working correctly.
How to Use
It appears that both the traditional Pages Router and the App Router styles are supported.
Since I find the pages-based approach easier to understand, I structured my directories as follows:
Directory Structure
Result
With this setup, the following pages can be displayed:
http://localhost:3000http://localhost:3000/abouthttp://localhost:3000/postshttp://localhost:3000/posts/1(Dynamic parameter page)
index.jsx or page.jsx as the Index Route
An index route refers to the default route page corresponding to a directory.
In this framework, pages/posts.jsx and pages/posts/index.jsx generate the same routing result.
From what I recall, with simple HTML structures, there was a distinction between paths ending with / and those without /. However, in this framework, URLs are standardized without the trailing /, and accessing a URL with / at the end does not result in a 404 but instead redirects properly.
How to Use Parameters
By naming the file [id].jsx, you can use parameters, which are accessible as props with the name id.
pages/posts/[id].jsx
export default function Post({ id }) {
return <h1>Post ID: {id}</h1>
}When accessing http://localhost:3000/posts/1, the following is displayed:
Post ID: 1Additionally, using the App Router style:
pages/posts/[id]/index.jsx will also work the same way.
How to Use Multiple Parameters
By naming the file [id]-[name].jsx with a - separator:
export default function Post({ id, name }) {
return (
<h1>
Post ID: {id}
{name}
</h1>
)
}You can use props in the same way.
If you access http://localhost:3000/posts/1-Name, the parameters will be correctly parsed.
By the way, if you want a route like http://localhost:3000/posts/1/Name,
you should structure your directories as follows:
pages/posts/[id]/[name]/index.jsx
The method to access the parameters via props remains the same.
I hope this information helps someone!





