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.
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.
With h3, you also have reloading out-of-the-box without any configuration using unjs/listhen.
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.
Multi Router
The second example is the Multi Router. In this example, we create many routers to split the logic.
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.
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
.