This content originally appeared on DEV Community and was authored by Sam Newby
Modern Express.js
h3 is a modern alternative to express.js built by the amazing unjs team. It's built with TypeScript so you get that typed magic straight out of the box. But enough of talking let's build an API with h3.
Install
We're going to use pnpm as our package manager but you could use npm or yarn if you like. Let's start by scaffolding a new project with:
pnpm init
That will create a base package.json
for us. Now, to install h3, run:
pnpm i h3
Let's also create a base file structure, create a new directory and an app.ts
: mkdir src && touch src/app.ts
. And finally let's add a script to run our server using listhen
which is another amazing package by the unjs team. Add the following to the scripts object in package.json
:
npx --yes listhen -w --open ./src/app.ts
Building the server
Now we can create our base server in the app.ts
file:
// Import h3 as npm dependency
import { createApp, createRouter, defineEventHandler } from h3";;
// Create an app instance
export const app = createApp();
// Create a new router and register it in app
const router = createRouter(); app.use(router);
// Add a new route that matches GET requests to / path
router.get(
"/", defineEventHandler((event) =>; {
return { message: "Tadaa!"; };
}),
);
Let's break down what we've just created:
- We're importing a number of exports from the
h3
package - We're going to create an app using the
createApp()
function we imported in step 1 - We're then creating a router using the
createRouter()
function we imported in step 1, and then telling our app we created in step 2 to use that router - We're then creating our first route which matches a GET request to the path
/
, if any request matches that criteria the server will respond with the value returned from thedefineEventHandler
, which in this case the function returns an object which contains a message. h3 will automatically convert that to JSON for us - Now if we run
pnpm run dev
listhen will automatically start our server and serve it at port 3000 We can now hit our server and see that amazing Tadaa! response!
Wrapping up
We've built a basic server with h3, get in there! But there is still so much we can do such as using adapters to make it into a Node.js server, or creating middleware or building session based auth with h3 but we will discuss in future content.
This content originally appeared on DEV Community and was authored by Sam Newby
Sam Newby | Sciencx (2024-10-21T12:19:54+00:00) Getting started with h3 by unjs. Retrieved from https://www.scien.cx/2024/10/21/getting-started-with-h3-by-unjs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.