Return an early response
The following middleware is in charge of returning an early Response in case of unauthenticated user access.
ts
// src/middlewares/guard.middleware.ts
import type { Get, UniversalMiddleware } from "@universal-middleware/core";
interface User {
id: string;
email: string;
}
// This middleware will return an early Response for unauthenticated users
const guardMiddleware = (() => (request, ctx) => {
if (!ctx?.user) {
return new Response("Unauthorized", {
status: 401,
});
}
// Using `satisfies` to not lose return type
}) satisfies Get<[], UniversalMiddleware<{ user?: User }>>;
// export default is mandatory
export default guardMiddleware;
After bundling and publishing this middleware, one can then use this middleware as follows:
ts
import { Hono } from "hono";
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-hono";
const app = new Hono();
app.use(guardMiddleware());
export default app;
ts
import { createApp } from "h3";
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-h3";
import { universalOnBeforeResponse } from "@universal-middleware/h3";
const app = createApp({
// /!\ This is required for universal-middleware to operate properly
onBeforeResponse: universalOnBeforeResponse,
});
app.use(guardMiddleware());
export default app;
ts
import { createRouter } from "@hattip/router";
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-hattip";
const app = createRouter();
app.use(guardMiddleware());
const hattipHandler = app.buildHandler();
export default hattipHandler;
ts
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware";
import { createHandler } from "@universal-middleware/cloudflare";
import { pipe } from "@universal-middleware/core";
// Cloudflare Workers have no internal way of representing a middleware
// Instead, we use the universal `pipe` operator
const wrapped = pipe(
guardMiddleware(),
() => {
return new Response("OK");
}
);
export default createHandler(() => wrapped)();
ts
// functions/_middlewares.ts
// See https://developers.cloudflare.com/pages/functions/middleware/
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-cloudflare-pages";
export const onRequest = guardMiddleware();
ts
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-express";
import express from "express";
const app = express();
app.use(guardMiddleware());
export default app;
ts
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-fastify";
import fastify from "fastify";
const app = fastify();
app.register(guardMiddleware());
export default app;
ts
import guardMiddleware from "@universal-middleware-examples/tool/middlewares/guard-middleware-elysia";
import Elysia from "elysia";
const app = new Elysia().use(guardMiddleware());
export default app;