Top Related Projects
The React Framework
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Quick Overview
Next Routes is a dynamic routing library for Next.js applications. It provides a simple and flexible way to define routes with parameters and handle them in your Next.js pages, offering a more traditional routing approach similar to Express.js.
Pros
- Simplifies route management in Next.js applications
- Supports dynamic route parameters and query strings
- Allows for easy integration of custom route handlers
- Compatible with server-side rendering (SSR) in Next.js
Cons
- May add complexity to smaller projects that don't require advanced routing
- Requires additional setup compared to Next.js's built-in file-based routing
- Limited documentation and community support compared to official Next.js routing
- May not be necessary for projects using the latest versions of Next.js with improved built-in routing
Code Examples
- Defining routes:
const routes = require('next-routes')()
routes
.add('index', '/')
.add('about', '/about')
.add('user', '/user/:id')
.add('post', '/blog/:slug')
- Using the Link component:
import { Link } from '../routes'
const Navigation = () => (
<nav>
<Link route="index"><a>Home</a></Link>
<Link route="about"><a>About</a></Link>
<Link route="user" params={{ id: 123 }}><a>User Profile</a></Link>
</nav>
)
- Programmatic navigation:
import { Router } from '../routes'
const handleClick = () => {
Router.pushRoute('post', { slug: 'hello-world' })
}
Getting Started
-
Install the package:
npm install next-routes
-
Create a
routes.js
file in your project root:const routes = require('next-routes')() routes .add('index', '/') .add('about', '/about') .add('user', '/user/:id') module.exports = routes
-
Update your
server.js
file:const next = require('next') const routes = require('./routes') const app = next({ dev: process.env.NODE_ENV !== 'production' }) const handler = routes.getRequestHandler(app) app.prepare().then(() => { createServer(handler).listen(3000) })
-
Use the
Link
component in your pages:import { Link } from '../routes' const IndexPage = () => ( <div> <h1>Welcome to Next.js!</h1> <Link route="about"><a>About</a></Link> </div> ) export default IndexPage
Competitor Comparisons
The React Framework
Pros of Next.js
- Comprehensive framework with built-in routing, server-side rendering, and API routes
- Large community and extensive ecosystem of plugins and integrations
- Regular updates and maintenance from Vercel, ensuring compatibility with latest web technologies
Cons of Next.js
- Steeper learning curve due to its extensive feature set
- Potentially overkill for simple projects that don't require all its features
- Less flexibility in customizing routing behavior compared to next-routes
Code Comparison
Next.js routing:
// pages/blog/[slug].js
export default function BlogPost({ slug }) {
return <h1>Blog Post: {slug}</h1>
}
export async function getStaticPaths() {
// ...
}
next-routes routing:
// routes.js
const routes = require('next-routes')()
routes.add('blog', '/blog/:slug')
// pages/blog.js
export default function BlogPost({ slug }) {
return <h1>Blog Post: {slug}</h1>
}
Next.js provides a more integrated routing solution with file-based routing, while next-routes offers a more flexible, centralized approach to defining routes. Next.js is better suited for larger projects with complex requirements, while next-routes may be preferable for simpler applications or those needing more control over routing behavior.
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Pros of TanStack Router
- Framework-agnostic, supporting React, Solid, Vue, and Svelte
- More powerful and flexible routing capabilities, including nested routes and type-safe routing
- Active development and maintenance with frequent updates
Cons of TanStack Router
- Steeper learning curve due to its more complex API and concepts
- Potentially overkill for simple projects that don't require advanced routing features
Code Comparison
next-routes:
const routes = require('next-routes')()
routes
.add('about', '/about')
.add('blog', '/blog/:slug')
TanStack Router:
import { Route } from '@tanstack/react-router'
const rootRoute = new Route({
getParentRoute: () => null,
path: '/',
})
const aboutRoute = new Route({
getParentRoute: () => rootRoute,
path: '/about',
})
Summary
next-routes is a simpler solution specifically designed for Next.js projects, offering an easy-to-use API for basic routing needs. TanStack Router, on the other hand, provides a more powerful and flexible routing solution that works across multiple frameworks. While TanStack Router offers more advanced features and type safety, it may be more complex to set up and use, especially for smaller projects. The choice between the two depends on the specific requirements of your project and your preferred framework.
Declarative routing for React
Pros of React Router
- More comprehensive routing solution with advanced features like nested routes and route-based code splitting
- Larger community and ecosystem, with extensive documentation and third-party integrations
- Flexible and can be used in various React-based projects, not limited to Next.js
Cons of React Router
- Steeper learning curve due to more complex API and concepts
- Requires more manual configuration and setup compared to Next Routes
- May introduce additional bundle size for smaller projects that don't need all features
Code Comparison
Next Routes:
const routes = require('next-routes')()
routes
.add('about', '/about')
.add('blog', '/blog/:slug')
React Router:
import { BrowserRouter, Route, Switch } from 'react-router-dom'
<BrowserRouter>
<Switch>
<Route path="/about" component={About} />
<Route path="/blog/:slug" component={Blog} />
</Switch>
</BrowserRouter>
Summary
React Router offers a more powerful and flexible routing solution suitable for complex applications, while Next Routes provides a simpler, more streamlined approach specifically tailored for Next.js projects. The choice between the two depends on the project's requirements, complexity, and the developer's familiarity with each library.
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Pros of wouter
- Lightweight and minimalistic (only ~1.5KB gzipped)
- Framework-agnostic, works with React, Preact, and other libraries
- Supports hooks-based routing for modern React applications
Cons of wouter
- Less feature-rich compared to next-routes
- May require additional setup for more complex routing scenarios
- Limited built-in support for nested routes
Code Comparison
next-routes:
const routes = require('next-routes')()
routes
.add('about', '/about', 'about')
.add('blog', '/blog/:slug', 'post')
module.exports = routes
wouter:
import { Route, Switch } from "wouter"
function App() {
return (
<Switch>
<Route path="/about" component={About} />
<Route path="/blog/:slug" component={BlogPost} />
</Switch>
)
}
next-routes offers a more configuration-based approach, while wouter provides a component-based routing system that closely resembles React Router. wouter's syntax is more inline with modern React practices, using hooks and functional components. However, next-routes integrates more tightly with Next.js and provides additional features specific to that framework.
Pros of reach/router
- More comprehensive routing solution with built-in accessibility features
- Supports nested routing and relative navigation
- Active community and regular updates
Cons of reach/router
- Steeper learning curve due to more advanced features
- May be overkill for simpler projects with basic routing needs
- Requires additional setup compared to Next.js built-in routing
Code Comparison
reach/router:
import { Router, Link } from "@reach/router"
const App = () => (
<Router>
<Home path="/" />
<Dashboard path="dashboard" />
</Router>
)
next-routes:
const routes = require('next-routes')()
routes
.add('index', '/')
.add('dashboard', '/dashboard')
module.exports = routes
Summary
reach/router offers a more feature-rich routing solution with built-in accessibility and nested routing support, making it suitable for complex applications. However, it may be excessive for simpler projects and requires additional setup.
next-routes provides a straightforward extension to Next.js routing, making it easier to implement dynamic routes. It's lightweight and integrates seamlessly with Next.js, but lacks some of the advanced features found in reach/router.
Choose reach/router for larger applications with complex routing needs, and next-routes for simpler Next.js projects requiring dynamic routing capabilities.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Dynamic Routes for Next.js
Deprecation Notice: This package was a popular choice in the early years of Next.js and is no longer maintained. Please check the Next.js docs for its current ways of routing.
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 = require('next-routes')
// Name Page Pattern
module.exports = routes() // ---- ---- -----
.add('about') // about about /about
.add('blog', '/blog/:slug') // blog blog /blog/:slug
.add('user', '/user/:id', 'profile') // user profile /user/:id
.add('/:noname/:lang(en|es)/:wow+', 'complex') // (none) complex /:noname/:lang(en|es)/:wow+
.add({name: 'beta', pattern: '/v3', page: 'v3'}) // 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
export default class Blog extends React.Component {
static async getInitialProps({query}) {
// query.slug
}
render() {
// this.props.url.query.slug
}
}
On the server
// server.js
const next = require('next')
const routes = require('./routes')
const app = next({dev: process.env.NODE_ENV !== 'production'})
const handler = routes.getRequestHandler(app)
// With express
const express = require('express')
app.prepare().then(() => {
express().use(handler).listen(3000)
})
// Without express
const {createServer} = require('http')
app.prepare().then(() => {
createServer(handler).listen(3000)
})
Optionally you can pass a custom handler, for example:
const handler = routes.getRequestHandler(app, ({req, res, route, query}) => {
app.render(req, res, route.page, query)
})
Make sure to use server.js
in your package.json
scripts:
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
On the client
Import Link
and Router
from your routes.js
file to generate URLs based on route definition:
Link
example
// pages/index.js
import {Link} from '../routes'
export default () => (
<div>
<div>Welcome to Next.js!</div>
<Link route="blog" params={{slug: 'hello-world'}}>
<a>Hello world</a>
</Link>
or
<Link route="/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.js
import React from 'react'
import {Router} from '../routes'
export default class Blog extends React.Component {
handleClick() {
// With route name and params
Router.pushRoute('blog', {slug: 'hello-world'})
// With route URL
Router.pushRoute('/blog/hello-world')
}
render() {
return (
<div>
<div>{this.props.url.query.slug}</div>
<button onClick={this.handleClick}>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 = module.exports = require('next-routes')({
Link: require('./my/link')
Router: require('./my/router')
})
Related links
- zeit/next.js - Framework for server-rendered React applications
- path-to-regexp - Express-style path to regexp
Top Related Projects
The React Framework
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot