All Projects → gvergnaud → Nextjs Dynamic Routes

gvergnaud / Nextjs Dynamic Routes

Licence: mit
[Deprecated] Super simple way to create dynamic routes with Next.js

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Nextjs Dynamic Routes

Awesome Nextjs
📔 📚 A curated list of awesome resources : books, videos, articles about using Next.js (A minimalistic framework for universal server-rendered React applications)
Stars: ✭ 6,812 (+4597.93%)
Mutual labels:  nextjs, isomorphic, routing
Next Routes
Universal dynamic routes for Next.js
Stars: ✭ 2,354 (+1523.45%)
Mutual labels:  nextjs, router, routing
Phprouter
PhpRouter is a powerful, minimal, and very fast HTTP URL router for PHP projects
Stars: ✭ 97 (-33.1%)
Mutual labels:  router, routing
Oh My Fullstack
🚀 Full stack web application skeleton (Next.js, Redux, RxJS, Immutable, Express)
Stars: ✭ 99 (-31.72%)
Mutual labels:  nextjs, isomorphic
React Page Layout
Create layouts for react
Stars: ✭ 117 (-19.31%)
Mutual labels:  router, routing
Corenavigation
📱📲 Navigate between view controllers with ease. 💫 🔜 More stable version (written in Swift 5) coming soon.
Stars: ✭ 69 (-52.41%)
Mutual labels:  router, routing
Lit Element Router
A LitElement Router (1278 bytes gzip)
Stars: ✭ 85 (-41.38%)
Mutual labels:  router, routing
Php Router
simple and flexible Router class for PHP. with Controllers and Middlewares support.
Stars: ✭ 111 (-23.45%)
Mutual labels:  router, routing
Routing
The Routing component maps an HTTP request to a set of configuration variables.
Stars: ✭ 7,080 (+4782.76%)
Mutual labels:  router, routing
Next Redux Wrapper
Redux wrapper for Next.js
Stars: ✭ 1,901 (+1211.03%)
Mutual labels:  nextjs, isomorphic
Django Macros Url
Django Macros URL. Routing must be simple as possible
Stars: ✭ 121 (-16.55%)
Mutual labels:  router, routing
Bsdrp
BSD Router Project
Stars: ✭ 126 (-13.1%)
Mutual labels:  router, routing
Restify Router
A router interface for restify that lets you aggregate route definitions and apply to a restify server
Stars: ✭ 45 (-68.97%)
Mutual labels:  router, routing
Url Mapper
Take a URL and map to functions, parsing params
Stars: ✭ 39 (-73.1%)
Mutual labels:  router, routing
Literoute
LiteRoute is easy transition for your app. Written on Swift 4
Stars: ✭ 90 (-37.93%)
Mutual labels:  router, routing
React Router Component
Declarative router component for React.
Stars: ✭ 879 (+506.21%)
Mutual labels:  router, routing
Buttermilk
beautifully simple isomorphic routing for React projects
Stars: ✭ 108 (-25.52%)
Mutual labels:  isomorphic, routing
Router5
Flexible and powerful universal routing solution
Stars: ✭ 1,704 (+1075.17%)
Mutual labels:  router, routing
Storeon Async Router
Asynchronous router for Storeon. It provides possibility for prefetch the data, lazy load, navigation cancellation, and routes modification on the fly.
Stars: ✭ 22 (-84.83%)
Mutual labels:  router, routing
Bidi
Bidirectional URI routing
Stars: ✭ 941 (+548.97%)
Mutual labels:  router, routing

Next.js Dynamic Routes

/!\ Deprecated, please don't use

Dynamic routes are now natively supported on Nextjs v9 and higher. This package will stay around on npm, but it is now unmaintained and there will be no new releases.


A dynamic routing solution for the awesome Next.js framework.

Why ?

Next.js introduced in it's V2 a programmatic routing API allowing you to serve your Next app from, for example, an express server:

// yourServer.js
server.get('/user/:id', (req, res) => {
  return app.render(req, res, '/user', req.params)
})
// ./pages/index.js
<Link href={`/user?id={id}`} as={`/user/${id}`}><a>Visit me!</a></Link>

But as the number of pages grows, it's getting a little hard to manage...

Introducing Dynamic Routes

npm install --save nextjs-dynamic-routes

Setup your routes

Create a routes.js file and list all your Dynamic routes. You don't have to list your regular routes, as Next.js will handle them as usual (but you can!).

const Router = require('nextjs-dynamic-routes')

const router = new Router()

router.add({ name: 'character', pattern: '/characters/:id' })

router.add({ name: 'film', pattern: '/films/:id' })

// if the name of your route is different from your component file name:
router.add({
  name: 'characterAndFilm',
  pattern: '/character-and-film/:characterId/:filmId',
  page: '/character-and-film'
})

module.exports = router

Setup your request handler

const express = require('express')
const next = require('next')
const Router = require('./routes')

const app = next({ dev: process.env.NODE_ENV !== 'production' })
const server = express()
const handle = Router.getRequestHandler(app)

app.prepare()
  .then(() => {
    server.get('*', (req, res) => handle(req, res))
    server.listen(3000)
  })

Use your routes

Then Nextjs Dynamic Routes exports a Link component. It's just like next/link, but it adds a route prop that let you refer to a route by its name.

// pages/index.js
import React from 'react'
import { Link } from '../routes'

export default () => (
  <ul>
    <li><Link route="character" id="1"><a>Luke Skywalker</a></Link></li>
    <li><Link route="character" id="2"><a>C-3PO</a></Link></li>
    <li><Link route="film" id="1"><a>A New Hope</a></Link></li>
    <li><Link route="film" id="2"><a>The Empire Strikes Back</a></Link></li>
    <li>
      <Link route="characterAndFilm" characterId="1" filmId="2">
        <a>The Empire Strikes Back and Luke Skywalker</a>
      </Link>
    </li>
  </ul>
)
// pages/character.js
import React from 'react'

export default class Character extends React.Component {
  static async getInitialProps({ query }) {
    return fetch(`//swapi.co/api/films/${query.id}`).then(x => x.json())
  }

  render() {
    return <p>{this.props.name}</p>
  }
}

Prefetching data

Next.js has this great feature allowing you to prefetch data for your next routes in the background.

You can benefit from that by simply putting a prefetch property on any Link :

<Link prefetch route="film" id="2"><a>The Empire Strikes Back</a></Link>

Imperative API

Router.pushRoute(name, params [, options])

import Router from '../routes'

<button onClick={() => Router.pushRoute('film', { id: 2 })}>
  Go to film 2
</button>

Router.replaceRoute(name, params [, options])

import Router from '../routes'

<button onClick={() => Router.replaceRoute('film', { id: 2 })}>
  Go to film 2
</button>

Router.prefetchRoute(name, params)

import Router from '../routes'

<button onClick={() => Router.prefetchRoute('film', { id: 2 })}>
  Prefetch film 2
</button>

Router.getRoutePath(name, params)

import Router from '../routes'

console.log(Router.getRoutePath('characterAndFilm', { characterId: 2, filmId: 5 }))
// => '/character-and-film/2/5'

Query params

The Link component has a queryParams prop which you can fill with an object of regular query parameters.

<Link prefetch route="film" id="2" queryParams={{ utm_campaign: 'website' }}>
  <a>The Empire Strikes Back</a>
</Link>

This will result in the following url: /films/2?utm_campaign=website.

You can use queryParams with the imperative API as well

// It doesn't work only for pushRoute, but for all the other methods as well.
Router.pushRoute('film', {
  id: 2,
  queryParams: {
    utm_campaign: 'website'
  }
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].