Back to Templates

Hono API with Unkey Middleware in Deno

How to create a minimal API with Hapi.js, including public and protected routes

Written by
Yash-1511
Framework
hapi
Language
Typescript
How to create a minimal API with Hapi.js, including public and protected routes

Hapi.js Unkey API Protection Example

This repository demonstrates how to create a minimal API with Hapi.js, including public and protected routes. The protected route is secured using Unkey.

Features

  • A public route that anyone can access.
  • A protected route that requires a valid Unkey token to access.

Prerequisites

  • Node.js
  • A Unkey account (to generate a root key and access tokens)

Quickstart

1. Clone the repository and install dependencies:

1git clone https://github.com/Yash-1511/hapi-unkey-template.git
2cd hapi-unkey-template
3npm install

2. Set up the environment:

  • In your Unkey account, navigate to Settings and generate a Root Key.
  • Create a .env file and add your Unkey root key:
1UNKEY_ROOT_KEY=your-unkey-root-key-here

3. Run the server:

1node server.js

The server will run on http://localhost:3000.

4. Available routes:

  • GET /public - This is a public route accessible by anyone.
  • GET /protected - This is a protected route, requiring a valid Unkey token.

5. Generate an API key in Unkey:

  • Go to your Unkey dashboard and create an API key.
  • You can use this API key as the bearer token when accessing the protected route.

6. Making requests:

Public Route:

You can access the public route by making a simple GET request:

1curl http://localhost:3000/public

You should get a response:

1{
2 "message": "This is a public route."
3}

Protected Route:

To access the protected route, you need to include the Unkey token as a bearer token in the request header. Replace your-unkey-api-key with the actual key you generated in Unkey.

1curl -H "Authorization: Bearer your-unkey-api-key" http://localhost:3000/protected

If the token is valid, you will get a response like this:

1{
2 "message": "This is a protected route, secured by Unkey."
3}

If the token is missing or invalid, you will get an error response:

1{
2 "error": "Invalid token"
3}

7. Troubleshooting:

  • Missing Authorization Header: Ensure you pass the Authorization: Bearer <token> header.
  • Invalid Token: Make sure the token you are using is valid and has not expired.

License

This project is licensed under the MIT License.

Protect your API.
Start today.

2500 verifications and 100K successful rate‑limited requests per month. No CC required.