next-routes
next-routes copied to clipboard
Nesting pages like default Next.js routing
With default Next.js routing that it's based on the file system, we can create nested pages like this:
pages
├── index.js => /
├── about.js => /about
└── auth
├── login.js => /auth/login
├── register.js => /auth/register
So, how can I implement this routing with next-routes
?
This example is working?
const routes = require('next-routes');
module.exports = routes()
.add({name: 'dashboard', pattern: '/', page: 'index'})
.add({name: 'login', pattern: '/auth/login', page: 'auth/login'})
.add({name: 'register', pattern: '/auth/register', page: 'auth/register'})
Note: I've used default Next.js routing, so I don't want change my file system for next-routes.
Try this
import routes from "next-routes"; module.exports = routes() .add("index", "/", "index") // Blog .add("blog") .add('blog.detail', '/blog/:id', 'blog/detail')
A workaround we can do is:
- duplicate the routes and change the params
- call it using Next.js link instead
- The page should be in
pages
root, like/pages/post.js
.
In my example below, pages/post
is using 2 dynamically params, so I solve it using 2 routes for the same page.
routes.add('category/[slug]', '/category/:slug');
routes.add('postSlug', '/post/:slug', 'post');
routes.add('postLang', '/post/:lang/:slug', 'post');
Case usage
In my category/[slug].js
component I'm calling the route as below:
<Link
href={{
pathname: '/post',
query: {
slug: postSlug
}
}}
as={`/post/${postSlug}`}
>
Read more »
</Link>
But if I need to call the post in other languages, I can use the following route:
<Link
href={{
pathname: '/post',
query: {
slug: postSlug,
lang: item.slug,
}
}}
as={`/post/${item.slug}/${postSlug}`}
>
{item.name}
</Link>
Issues related: #296 #291 Related topic: https://stackoverflow.com/a/59259988/3332734