Skip to content

Open-source status page, incident response and uptime monitoring

blog: how to secure your api routes with unkey (#335)

Maximilian Kaskec26cf5db0157
diff --git a/apps/web/public/assets/posts/secure-api-with-unkey/unkey-landing.png b/apps/web/public/assets/posts/secure-api-with-unkey/unkey-landing.png
new file mode 100644
index 000000000..23409d913
Binary files /dev/null and b/apps/web/public/assets/posts/secure-api-with-unkey/unkey-landing.png differ
diff --git a/apps/web/src/content/posts/secure-api-with-unkey.mdx b/apps/web/src/content/posts/secure-api-with-unkey.mdx
new file mode 100644
index 000000000..8e0866157
--- /dev/null
+++ b/apps/web/src/content/posts/secure-api-with-unkey.mdx
@@ -0,0 +1,209 @@
+---
+title: How to secure your API with Unkey and Hono.js Middleware
+description: The simplest way to secure your API routes within seconds.
+author:
+ name: Maximilian Kaske
+ url: https://twitter.com/mxkaske
+publishedAt: 2023-10-01
+image: /assets/posts/secure-api-with-unkey/unkey-landing.png
+---
+
+## Introduction
+
+Why do we need to secure our APIs? Well, there are many reasons for that. The
+most important one is that we want to protect your data from unauthorized
+access.
+
+We will learn how to secure our [Hono.js](https://hono.dev) API server with
+[Unkey](https://unkey.dev).
+
+Unkey is a service that allows you to create and manage API keys. It includes
+useful features like:
+
+- **Rate limiting**: avoid getting DDoSed
+- **Temporary keys**: when working on free trials
+- **Key limitation**: limit the number of max. requests
+
+**The best part**: We have no additional database migration or setup to do. Just
+use the Unkey API and/or SDK to create, revoke and verify keys.
+
+Hono is similar to express just hipper and runs on the edge.
+
+### How does OpenStatus use Unkey?
+
+Whenever OpenStatus creates an API key, we will send a request to the Unkey API
+using their [Typescript SDK](https://docs.unkey.dev/libraries/js/overview) with
+the a specific `ownerId` which will be the `workspaceId` in our case. The user
+will get an API key back which they can use to access their content via our API
+route. Unkey will match the API key to the `ownerId` and we will be able to
+validate that the request is the owner of the `workspaceId`.
+
+As an example, here the Next.js `server action` (see
+[GitHub](<https://github.com/openstatusHQ/openstatus/blob/main/apps/web/src/app/app/(dashboard)/%5BworkspaceSlug%5D/settings/_components/api-keys/actions.ts>))
+to allow users to create and revoke their own API keys:
+
+```ts title="actions.ts"
+"use server";
+
+import { Unkey } from "@unkey/api";
+
+const unkey = new Unkey({ token: process.env.UNKEY_TOKEN });
+
+export async function create(ownerId: number) {
+ const key = await unkey.keys.create({
+ apiId: env.UNKEY_API_ID,
+ ownerId: String(ownerId), // workspaceId
+ prefix: "os", // os_1234567890
+ // include more options like 'ratelimit', 'expires', 'remaining'
+ });
+ return key;
+}
+
+export async function revoke(keyId: string) {
+ const res = await unkey.keys.revoke({ keyId });
+ return res;
+}
+```
+
+To test key creation, you can simply go to the
+[Unkey Dashboard](http://unkey.dev/app) and create an API key manually instead
+of using the SDK. The SDK is useful once you want your users to create API keys
+programmatically.
+
+## Getting started
+
+Checkout [hono.dev](https://hono.dev) if you want to set up a new project or
+follow along if you already have a Hono.js project.
+
+We will pinpoint the most important parts of the setup. You can find the full
+code source on
+[GitHub](https://github.com/openstatusHQ/openstatus/tree/main/apps/server).
+
+### Create the base path
+
+That's as simple as it looks. Create a `new Hono()` instance and define the
+routes (`route`) and middlewares (`use`).
+
+For the sake of this example, we only consider the `/api/v1/monitor` route.
+
+```ts title="index.ts"
+import { middleware } from "./middleware";
+import { monitorApi } from "./monitor";
+
+export type Variables = { workspaceId: string }; // Context
+
+const api = new Hono<{ Variables: Variables }>().basePath("/api/v1");
+
+api.use("/*", middleware);
+api.route("/monitor", monitorApi);
+
+export default app;
+```
+
+### Create the middleware
+
+The middleware will automatically be applied to all routes that match the path
+`/api/v1/*`. We will use the `x-openstatus-key` request header to append the API
+key and verify it on our server.
+
+The Hono [Context](https://hono.dev/api/context) will be used to store the
+`workspaceId` we are retrieving from Unkey and sharing it across the
+application.
+
+Here, we are verifying the API key via the
+[`@unkey/api`](https://docs.unkey.dev/libraries/js/overview) package. It returns
+either an `error` or the `result.valid` whether or not to grant access to the
+user.
+
+```ts title="middleware.ts"
+import { verifyKey } from "@unkey/api";
+import type { Context, Next } from "hono";
+
+import type { Variables } from "./index";
+
+export async function middleware(
+ c: Context<{ Variables: Variables }, "/api/v1/*">,
+ next: Next,
+) {
+ const key = c.req.header("x-openstatus-key");
+
+ if (!key) return c.text("Unauthorized", 401);
+
+ const { error, result } = await verifyKey(key);
+
+ // up to you if you want to pass the actual message to your users
+ // or simply return "Internal Server Error"
+ if (error) return c.text(error.message, 500);
+ if (!result.valid) return c.text("Unauthorized", 401);
+
+ c.set("workspaceId", result.ownerId);
+
+ await next();
+}
+```
+
+### Create the route
+
+Every route, here `monitorApi`, will have access to the `workspaceId` via the
+Context and therefore can query the database for the workspace.
+
+```ts title="monitor.ts"
+import type { Variables } from "./index";
+
+export const monitorApi = new Hono<{ Variables: Variables }>();
+
+monitorApi.get("/:id", async (c) => {
+ const workspaceId = c.get("workspaceId");
+ const { id } = c.req.valid("param");
+
+ // ...fetch data from your database [e.g. via Drizzle ORM]
+ const monitor = await db
+ .select()
+ .from(monitor)
+ .where(
+ and(
+ eq(monitor.id, Number(id)),
+ eq(monitor.workspaceId, Number(workspaceId)),
+ ),
+ )
+ .get();
+
+ return c.json(monitor);
+});
+```
+
+Read more about the Hono path parameter `":id"`
+[here](https://hono.dev/api/routing#path-parameter).
+
+### Test it
+
+Once your project is running, you can test your implementation with the
+following `curl` command to access your monitor with the id `1`:
+
+```bash
+curl --location 'http://localhost:3000/api/v1/monitor/1' \
+--header 'x-openstatus-key: os_1234567890'
+```
+
+For OpenStatus, we are running our Hono.js server on [fly.io](https://fly.io)
+with [bun](https://bun.sh) via `bun run src/index.ts`.
+
+> We have included the
+> [`@hono/zod-openapi`](https://github.com/honojs/middleware/tree/main/packages/zod-openapi)
+> plugin to generate an OpenAPI spec out of the box. Read more about the
+> supported endpoints in our
+> [docs](https://docs.openstatus.dev/rest-api/openapi).
+
+## Conclusion
+
+Et voilà. We have secured our API with Unkey and the Hono.js middleware, only
+allowing authorized users to access their data.
+
+Unkey increases our velocity and **helps us focus on what's relevant** to the
+user, not the infrastructure behind it. We also get **key verification
+insights** out of the box and can target specific users based on their usage.
+
+[@chronark\_](http://twitter.com/chronark_) has recently published an
+[`@unkey/hono`](https://docs.unkey.dev/libraries/ts/hono) package that uses a
+similar implementation under the hood, reducing some boilerplate code for you.
+Highly recommend checking it out if you are using Hono.js.
diff --git a/apps/web/src/contentlayer/plugins/pretty-code.ts b/apps/web/src/contentlayer/plugins/pretty-code.ts
index 2b9da8976..3f692179f 100644
--- a/apps/web/src/contentlayer/plugins/pretty-code.ts
+++ b/apps/web/src/contentlayer/plugins/pretty-code.ts
@@ -1,27 +1,24 @@
import rehypePrettyCode from "rehype-pretty-code";
import type * as unified from "unified";
+// props to https://rehype-pretty-code.netlify.app/
+
const prettyCode: unified.Pluggable<any[]> = [
rehypePrettyCode,
{
- // prepacked themes
- // https://github.com/shikijs/shiki/blob/main/docs/themes.md
theme: "github-light",
-
- // https://stackoverflow.com/questions/76549262/onvisithighlightedline-cannot-push-classname-using-rehype-pretty-code
- // FIXME: maybe properly type this
onVisitLine(node: any) {
// Prevent lines from collapsing in `display: grid` mode, and
// allow empty lines to be copy/pasted
if (node.children.length === 0) {
node.children = [{ type: "text", value: " " }];
}
- node.properties.className = ["line"]; // add 'line' class to each line in the code block
},
-
- // FIXME: maybe properly type this
onVisitHighlightedLine(node: any) {
- node.properties.className?.push("line--highlighted");
+ node.properties.className.push("highlighted");
+ },
+ onVisitHighlightedWord(node: any) {
+ node.properties.className = ["word"];
},
},
];
diff --git a/apps/web/src/styles/syntax-highlighting.css b/apps/web/src/styles/syntax-highlighting.css
index 2ab60836f..82c68bd12 100644
--- a/apps/web/src/styles/syntax-highlighting.css
+++ b/apps/web/src/styles/syntax-highlighting.css
@@ -1,75 +1,35 @@
-/* span entire width */
-pre > code {
- display: grid;
-}
-
-.prose pre {
- margin: 0;
- padding: 0;
-}
-
-div[data-rehype-pretty-code-fragment] {
- overflow: hidden;
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
- /* stylist preferences */
- background-color: var(--muted-foreground);
- border-radius: 0.5rem;
- width: 100%;
- margin: 1rem 0;
+div[data-rehype-pretty-code-title] {
+ @apply -mb-5 ml-4 font-mono text-sm;
}
-div[data-rehype-pretty-code-fragment] pre {
- overflow-x: auto;
-
- /* stylist preferences */
- padding-top: 0.5rem;
- padding-bottom: 0.5rem;
- font-size: 0.875rem;
- line-height: 1.5rem;
- @apply text-xs sm:text-sm lg:text-base;
+div[data-rehype-pretty-code-fragment] code {
+ display: grid;
+ counter-reset: line;
}
-div[data-rehype-pretty-code-title] {
- /* stylistic preferences */
- margin-bottom: 0.125rem;
- border-radius: 0.375rem;
- padding-left: 0.75rem;
- padding-right: 0.75rem;
- padding-top: 0.25rem;
- padding-bottom: 0.25rem;
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
- "Liberation Mono", "Courier New", monospace;
- font-size: 0.75rem;
- line-height: 1rem;
+div[data-rehype-pretty-code-fragment] code .line {
+ @apply border-l-2 border-transparent px-5 py-0;
}
-div[data-rehype-pretty-code-fragment] .line {
- /* stylistic preferences */
- padding-left: 0.5rem;
- padding-right: 0.75rem;
-
- border-left-width: 4px;
- border-left-color: transparent;
+div[data-rehype-pretty-code-fragment] code[data-line-numbers] .line::before {
+ counter-increment: line;
+ content: counter(line);
+ @apply mr-8 inline-block w-4 text-right text-gray-500;
}
-div[data-rehype-pretty-code-fragment] .line--highlighted {
- border-left-color: hsl(var(--border));
- background-color: hsl(var(--muted));
+div[data-rehype-pretty-code-fragment] code .word {
+ @apply rounded bg-gray-100/50 p-1;
}
-/* https://rehype-pretty-code.netlify.app/#:~:text=%60%60%60-,Line%20numbers,-CSS%20counters%20can */
-pre > code[data-line-numbers] {
- counter-reset: lineNumber;
+div[data-rehype-pretty-code-fragment] code .highlighted {
+ @apply border-l-2 border-gray-500 bg-gray-100/25;
}
-code[data-line-numbers] .line::before {
- counter-increment: lineNumber;
- content: counter(lineNumber);
- display: inline-block;
- text-align: right;
- color: hsl(var(--muted-foreground) / 0.5);
-
- /* stylistic preferences */
- margin-right: 0.75rem;
- width: 1rem;
-}
+/* OVERWRITE prose-rem default */
+/* div[data-rehype-pretty-code-fragment] pre {
+ @apply px-0 py-5;
+} */