Dynamic Routes for Next.js
Easy to use universal dynamic routes for Next.js
- Express-style route and parameters matching
- Request handler middleware for express & co
Link
andRouter
that generate URLs by route definition
How to use
Install:
npm install next-routes --save
Create routes.js
inside your project:
const routes = // Name Page Patternmoduleexports = // ---- ---- ----- // about about /about // blog blog /blog/:slug // user profile /user/:id // (none) complex /:noname/:lang(en|es)/:wow+ // beta v3 /v3
This file is used both on the server and the client.
API:
routes.add([name], pattern = /name, page = name)
routes.add(object)
Arguments:
name
- Route namepattern
- Route pattern (like express, see path-to-regexp)page
- Page inside./pages
to be rendered
The page component receives the matched URL parameters merged into query
Component static async { // query.slug } { // this.props.url.query.slug }
On the server
// server.jsconst next = const routes = const app = const handler = routes // With expressconst express = app // Without expressconst createServer = app
Optionally you can pass a custom handler, for example:
const handler = routes
Make sure to use server.js
in your package.json
scripts:
"scripts":
On the client
Import Link
and Router
from your routes.js
file to generate URLs based on route definition:
Link
example
// pages/index.jsimport Link from '../routes' <div> <div>Welcome to Nextjs!</div> <Link ='blog' => <a>Hello world</a> </Link> or <Link ='/blog/hello-world'> <a>Hello world</a> </Link> </div>
API:
<Link route='name'>...</Link>
<Link route='name' params={params}> ... </Link>
<Link route='/path/to/match'> ... </Link>
Props:
route
- Route name or URL to match (alias:to
)params
- Optional parameters for named routes
It generates the URLs for href
and as
and renders next/link
. Other props like prefetch
will work as well.
Router
example
// pages/blog.jsimport React from 'react'import Router from '../routes' Component { // With route name and params Router // With route URL Router } { return <div> <div>thispropsurlqueryslug</div> <button =>Home</button> </div> }
API:
Router.pushRoute(route)
Router.pushRoute(route, params)
Router.pushRoute(route, params, options)
Arguments:
route
- Route name or URL to matchparams
- Optional parameters for named routesoptions
- Passed to Next.js
The same works with .replaceRoute()
and .prefetchRoute()
It generates the URLs and calls next/router
Optionally you can provide custom Link
and Router
objects, for example:
const routes = moduleexports = Link: Router:
Related links
- zeit/next.js - Framework for server-rendered React applications
- path-to-regexp - Express-style path to regexp