Examples

From Express.js to h3

Through various examples, let's see how easy it is to use h3 if you are familiar with Express.js.


During this guide, we will reproduce many examples from the Express.js documentation to show you how to do the same thing with h3.

If you are not familiar with Express.js, you can safely skip this guide.

The idea is to show you how similar h3 is to Express.js. Once you understand the similarities, you will be able to use h3 without any problem if you are familiar with Express.js.

Even if h3 seems to be similar to Express.js, it does not mean that Express.js is still viable. Express.js is an old framework that has not evolved for a long time. It's not a good choice for new projects since it can easily lead to security issues and memory leaks.

With h3, you also have reloading out-of-the-box without any configuration using unjs/listhen.

You can run every h3 examples using npx --yes listhen -w ./app.ts.

Hello World

The first example from the Express.js documentation is the Hello World.

The code is pretty simple:

Let's see how to do the same thing with h3:

Then, you can use npx --yes listhen -w ./app.ts to start the server and go to http://localhost:3000 to see the result.

Read more in Guide > App.

Multi Router

The second example is the Multi Router. In this example, we create many routers to split the logic.

For some facilities, we group every files in the same one.

Using h3, we can do the same thing:

It's quite similar. The main difference is that we have to use useBase to define a base path for a router.

Read more in Guide > Router.

Params

The third example is the Params. In this example, we use parameters in the route.

Using h3, we can do the same thing:

With h3, we do not have a param method. Instead, we use getRouterParam or getValidatedRouterParams to validate the params. It's more explicit and easier to use. In this example, we use Zod but you are free to use any other validation library.

Cookies

The fourth example is the Cookies. In this example, we use cookies.

Using h3, we can do the same thing:

With h3, we do not have a cookieParser middleware. Instead, we use getCookie and setCookie to get and set cookies. It's more explicit and easier to use.

Middleware

When using express, we usually handle requests with middleware.

For instance, here we use morgan to handle request logging.

In h3, we can also directly use middleware from the express ecosystem.

This can be easily achieved by wrapping with fromNodeMiddleware.