DEV Community

Sam Newby for Vizalo

Posted on • Edited on

Getting started with h3 by unjs

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
Enter fullscreen mode Exit fullscreen mode

That will create a base package.json for us. Now, to install h3, run:

pnpm i h3
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!"; }; 
        }), 
); 
Enter fullscreen mode Exit fullscreen mode

Let's break down what we've just created:

  1. We're importing a number of exports from the h3 package
  2. We're going to create an app using the createApp() function we imported in step 1
  3. 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
  4. 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 the defineEventHandler, which in this case the function returns an object which contains a message. h3 will automatically convert that to JSON for us
  5. 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.

Top comments (0)