Git Product home page Git Product logo

routex.js's Introduction

Routex.js

Yes, another library to handle dynamic routes in Next.js


Features

  • ๐ŸŒŒ Universal
  • ๐Ÿƒ Tree shakeable
  • ๐Ÿœ Not tiny, but pretty small
  • ๐Ÿ”— Build your custom <Link /> on top of it
  • ๐ŸŽ‰ Same routes contract as next-routes name, pattern, page
  • ๐Ÿš€ Up to date path-to-regexp dependency
  • ๐ŸŒ Compatible with multi-domain routing (a.k.a routes localization)
  • ๐Ÿ˜Ž 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);
});

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

  • 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.

routex.js's People

Contributors

alexhoma avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

routex.js's Issues

Return a function directly instead of an object

Description
It's not a bug. I've found a way to use the link function in a simpler way. The createRouteLinks function returns an object with only one function inside and I think this can be changed.

Describe alternatives you've considered
Return a function instead of an object, to simplify the usage. โš ๏ธ It will break the library API.

Related code:

routex.js/src/client.js

Lines 60 to 85 in 192e401

function createRouteLinks(routeDefinitions) {
const composedRoutes = composeRoutes(routeDefinitions);
return {
link({ route: routeName, params = {} }) {
if (!routeName) {
throw new Error(`Function link() should have a route name`);
}
let foundRoute = findRouteByName(composedRoutes, routeName);
if (!foundRoute) {
throw new Error(
`Route name "${routeName}" is not defined in your route definitions`
);
}
const { as, href } = foundRoute.getLinkProps(params);
return {
as,
href
};
}
};
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.