loading...

Routex v1.0.0: Modern Node Router

cretezy profile image Charles Crete ・2 min read

Today I have the pleasure to release Routex v1.0.0, after a year of testing and improvements. It now has a list of first-party packages for common uses, such as a body-parser, cookies, and hooks (to be talked in another article!)

Routex is a Node router designed with modern features such as async/await and TypeScript in mind. Its API surface is small and uses few dependencies itself. I now consider it production-ready after using it for many months.

Let's look at a couple of examples and use-cases for Routex, first with the installation.

yarn add routex
# or
npm install routex

Next up, we can create our entry point (using TypeScript here)

import { JsonBody, Routex, TextBody, ICtx } from "routex";

// Port will be parsed if a string
const port = process.env.PORT || 3000;

// Create the application
const app = new Routex();

// Setup a GET route on /
app.get("/", () => {
  // Returning a body, in this case text 
  return new TextBody("Hello world!");
});

// Adding parameters to a route. Notice how `/` can be before or after?
app.get("/:name", (ctx: ICtx) => {
  // Using the `ctx` object to get data, and return some JSON
  return new JsonBody({ hello: ctx.params.name });
});

// Start the server
app.listen(port).then(() => console.log(`Listening on ${port}`));

This is a simple example server, but what about middlewares?

import { ICtx, ErrorWithStatusCode } from "routex";

function authMiddleware(ctx: ICtx) {
  if(!ctx.headers.authorization) {
    throw new ErrorWithStatusCode(400, "Not authorized");
  }
}

// Global
app.middleware(authMiddleware);

// Route
app.get("/", [authMiddleware, handler]);

As you see, errors are used a flow control, making it stop the execution of the request at any point. Error display can be controlled using app.errorHandler

Request data also now has a place to live, inside ctx.data. No more req.user:

async function authMiddleware(ctx: ICtx) {
  // ...

  const user = await getUser();
  ctx.data.user = user;
}

app.get("/", [
  authMiddleware, 
  (ctx: ICtx) => {
    return new JsonBody({ name: ctx.data.user.name });
  },
]);

All middlewares and handlers can use async/await with native support.

What about the vast ecosystem of Express middlewares? Worry not, as Routex comes with the useExpress wrapper, making it easy to use most Express middlewares with no effort:

import { useExpress } from "routex";
import cors from "cors";

app.middleware(useExpress(cors()));

Now that Routex v1.0.0 is released, I am excited to share it with you and get feedback (please open an issue!).

You can see more of Routex at routex.js.org or view the project on GitHub.

Discussion

markdown guide
 

Looking Interesting!

Well Try it and give you feedback later on

Good Job , just follow up with the bugs and security issues