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

routex.js

v1.0.2

Published

Tiny library to manage dynamic and universal routes in Next.js

Downloads

30

Readme

Features

  • :milky_way: Universal
  • :leaves: Tree shakeable
  • :ant: Not tiny, but pretty small
  • :link: Build your custom <Link /> on top of it
  • :tada: Same routes contract as next-routes name, pattern, page
  • :rocket: Up to date path-to-regexp dependency
  • :earth_africa: Compatible with multi-domain routing (a.k.a routes localization)
  • :sunglasses: Cool name!

Inspired by next-routes and next-minimal-routes.

Install

Install routex in your Next.js project:

npm i routex.js

Using yarn:

yarn add routex.js

Setup

Route definitions

Okay, so now we have installed routex. First of all we'll need to declare our application routes. So let's create a routes.js file:

module.exports = [
  {
    name: 'index',
    pattern: '/',
  },
  {
    name: 'post',
    pattern: '/post/:slug',
    page: 'post',
  },
  {
    name: 'tags',
    pattern: '/tags{-:id}?', // optional id param
    page: 'tags',
  },
];

If you need more info on how to create the route patterns check the path-to-regexp documentation: pillarjs/path-to-regexp.

Server getRequestHandler()

Once routes are declared, we want to handle it whenever a user loads any existing url in our application. So here we need to create our routex requestHandlerMiddleware in our server.js file, passing the next.js instance (nextApp) and our route definitions (routes) like this:

const express = require('express');
const next = require('next');
const nextApp = next({ dev: process.env.NODE_ENV !== 'production' });
const routes = require('./routes');
const { getRequestHandler } = require('routex.js');

const routexHandlerMiddleware = getRequestHandler(nextApp, routes);

nextApp.prepare().then(() => {
  express()
    .use(routexHandlerMiddleware);
    .listen(3000);
});

Client link()

Hooray! our server now handles dynamic routes. But now we need a way to create link components to point to that dynamic routes. So let's create a file CustomLink.js to use in our components.

import NextLink from 'next/link';
import { createRouteLinks } from 'routex.js';
import routes from './routes';

const { link } = createRouteLinks(routes);

export default function CustomLink({ children, route, params }) {
  return (
    <NextLink {...link({ route, params: { ...params } })}>
      <a>{children}</a>
    </NextLink>
  );
}

The createRouteLinks function transforms and closures all your routes and returns a new link function. This link is the one that will provide to the <NextLink /> component the as and href props. And it needs this two parameters:

  • route: a route name, the one that you have in the route definiton.
  • params: all dynamic params

And this is how you'll use your <CustomLink /> component:

import CustomLink from './CustomLink';

export default () => (
  <>
    This is an example page component:
    <CustomLink
      route="post"
      params={{
        slug: 'next-js-post',
      }}
    >
      Next.js post link
    </Link>
  </>
);

The output that will return your <CustomLink /> will be exactly the same that if you create a link using the current Next.js Link, like I'll show you in this example:

import NextLink from 'next/link';

export default () => (
  <NextLink as="/post/next-js-post" href="/post?slug=next-js-post">
    <a>Next.js post link</a>
  </NextLink>
);

Currently, there is no imperative way to change your app route using routex.js, like the next-routes' Router.pushRoute(route, params, options), because I didn't need it at all in my current applications. But I'm open to add it if someone finds it interesting. Since then, I'll try to keep this library as simple as possible.

For more information have a look into the example app directory.

Demos

Basic dynamic routing

Multi-domain routing (a.k.a localized routing)

Check this code example here: examples/with-route-localization

Motivation

Check out this blog post to know some of the reasons why I've decided to create another routing library: alexhoma.com/projects/routexjs-yet-another-router-for-nextjs

Things to do

  • [x] Add an example with multi-domain application
  • [ ] Since routex.js doesn't need React at all, add an example with other Next.js integrations, like Preact, inferno, etc.
  • [ ] Avoid loading all route definitions in client side, only the ones we use per page

Contributions

If you want to suggest a change, feature or any question, feel free to open an issue or a pull request. But check the contributing file before you go.