npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lung-next-routes-with-locale

v1.3.4

Published

Easy to use locale-based dynamic routes for Next.js

Downloads

2

Readme

Dynamic Routes with localization for Next.js

Based on Next-Routes with these changes:

  • No support for unnamed routes
  • Route can be added only by name, locale and pattern (and optionally page) or options object
  • Link and Router generate URLs only by route definition (name + params)
  • URLs are prefixed with locale (ie. /en/about)
  • Routes can have data object (if you generate routes dynamically you can pass custom data there)
  • default RequestHandler set locale and nextRoute properties on request (you can get data with req.nextRoute.data)

How to use

Install:

npm install next-routes-with-locale --save

Create routes.js inside your project:

const routes = module.exports = require('next-routes-with-locale')({ locale: 'en' })

routes
.add('about', 'en', '/about')
.add('blog', 'en', '/blog/:slug')
.add('blog', 'en', '/blog/:slug', {myCustom: 'data'})
.add('user', 'en', '/user/:id', 'profile', {myCustom: 'data'})
.add({name: 'beta', locale: 'en', pattern: '/v3', page: 'v3'})
.add('about', 'cs', '/o-projektu')
.add('blog', 'cs', '/blog/:slug')
.add('user', 'cs', '/uzivatel/:id', 'profile')
.add({name: 'beta', locale: 'cs', pattern: '/v3', page: 'v3'})

This file is used both on the server and the client.

API:

  • routes.add(name, locale, pattern = /name, page = name, data)
  • routes.add(object)

Arguments:

  • name - Route name
  • locale - Locale of the route
  • pattern - Route pattern (like express, see path-to-regexp)
  • page - Page inside ./pages to be rendered; can be ommited
  • data - Custom data object

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)
})

RequestHandler automatically sets req.locale to locale of matched route so you can use it in your app.

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 href='blog' params={{slug: 'hello-world'}}>
      <a>Hello world</a>
    </Link>
    or
    <Link href='blog' locale='cs' params={{slug: 'ahoj-svete'}}>
      <a>Hello world</a>
    </Link>
  </div>
)

API:

  • <Link href='name'>...</Link>
  • <Link href='name' locale='locale'>...</Link>
  • <Link href='name' params={params}> ... </Link>
  • <Link href='name' locale='locale' params={params}> ... </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 name and params and explicit locale
    Router.pushRoute('blog', {slug: 'hello-world'}, 'en')
  }
  render () {
    return (
      <div>
        <div>{this.props.url.query.slug}</div>
        <button onClick={this.handleClick}>Home</button>
      </div>
    )
  }
}

API:

  • Router.pushRoute(route, params) - automatically get current locale
  • Router.pushRoute(route, params, locale)
  • Router.pushRoute(route, params, locale, options)

Arguments:

  • route - Route name
  • locale - Route locale
  • params - Optional parameters for named routes
  • options - 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