fix: middleware state reset between middlewares (#1500)
This commit is contained in:
@@ -0,0 +1,201 @@
|
|||||||
|
---
|
||||||
|
description: |
|
||||||
|
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
|
||||||
|
---
|
||||||
|
|
||||||
|
A middleware is defined in a `_middleware.ts` file. It will intercept the
|
||||||
|
request in order for you to perform custom logic before or after the route
|
||||||
|
handler. This allows modifying or checking requests and responses. Common
|
||||||
|
use-cases for this are logging, authentication, and performance monitoring.
|
||||||
|
|
||||||
|
Each middleware gets passed a `next` function in the context argument that is
|
||||||
|
used to trigger child handlers. The `ctx` also has a `state` property that can
|
||||||
|
be used to pass arbitrary data to downstream (or upstream) handlers. This
|
||||||
|
`state` is included in `PageProps` by default, which is available to both the
|
||||||
|
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
||||||
|
[routes](/docs/concepts/routes.md). `ctx.state` is normally set by modifying its
|
||||||
|
properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
|
||||||
|
entire object like `ctx.state = { loggedIn = true }`.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// routes/_middleware.ts
|
||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
data: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handler(
|
||||||
|
req: Request,
|
||||||
|
ctx: MiddlewareHandlerContext<State>,
|
||||||
|
) {
|
||||||
|
ctx.state.data = "myData";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
resp.headers.set("server", "fresh server");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// routes/myHandler.ts
|
||||||
|
export const handler: Handlers<any, { data: string }> = {
|
||||||
|
GET(_req, ctx) {
|
||||||
|
return new Response(`middleware data is ${ctx.state.data}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Middlewares are scoped and can be layered. This means a project can have
|
||||||
|
multiple middlewares, each covering a different set of routes. If multiple
|
||||||
|
middlewares cover a route, they will all be run, in order of specificity (least
|
||||||
|
specific first).
|
||||||
|
|
||||||
|
For example, take a project with the following routes:
|
||||||
|
|
||||||
|
```
|
||||||
|
└── routes
|
||||||
|
├── _middleware.ts
|
||||||
|
├── index.ts
|
||||||
|
└── admin
|
||||||
|
├── _middleware.ts
|
||||||
|
└── index.ts
|
||||||
|
└── signin.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
For a request to `/` the request will flow like this:
|
||||||
|
|
||||||
|
1. The `routes/_middleware.ts` middleware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
|
||||||
|
|
||||||
|
For a request to `/admin` the request flows like this:
|
||||||
|
|
||||||
|
1. The `routes/_middleware.ts` middleware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||||
|
middleware.
|
||||||
|
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
|
||||||
|
|
||||||
|
For a request to `/admin/signin` the request flows like this:
|
||||||
|
|
||||||
|
1. The `routes/_middleware.ts` middleware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||||
|
middleware.
|
||||||
|
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
|
||||||
|
|
||||||
|
A single middleware file can also define multiple middlewares (all for the same
|
||||||
|
route) by exporting an array of handlers instead of a single handler. For
|
||||||
|
example:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// routes/_middleware.ts
|
||||||
|
|
||||||
|
export const handler = [
|
||||||
|
async function middleware1(req, ctx) {
|
||||||
|
// do something
|
||||||
|
return ctx.next();
|
||||||
|
},
|
||||||
|
async function middleware2(req, ctx) {
|
||||||
|
// do something
|
||||||
|
return ctx.next();
|
||||||
|
},
|
||||||
|
];
|
||||||
|
```
|
||||||
|
|
||||||
|
It should be noted that `middleware` has access to route parameters. If you're
|
||||||
|
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
|
const currentTenant = ctx.params.tenant;
|
||||||
|
//do something with the tenant
|
||||||
|
const resp = await ctx.next();
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
|
||||||
|
the value of `acme` in your middleware.
|
||||||
|
|
||||||
|
## Middleware Destination
|
||||||
|
|
||||||
|
To set the stage for this section, `MiddlewareHandlerContext` looks like this:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface MiddlewareHandlerContext<State = Record<string, unknown>> {
|
||||||
|
next: () => Promise<Response>;
|
||||||
|
state: State;
|
||||||
|
destination: router.DestinationKind;
|
||||||
|
remoteAddr: {
|
||||||
|
transport: "tcp" | "udp";
|
||||||
|
hostname: string;
|
||||||
|
port: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
and `router.DestinationKind` is defined like this:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||||
|
```
|
||||||
|
|
||||||
|
This is useful if you want your middleware to only run when a request is headed
|
||||||
|
for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
||||||
|
create a `_middleware.ts` file in the `routes` folder like this:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
|
console.log(ctx.destination);
|
||||||
|
console.log(req.url);
|
||||||
|
const resp = await ctx.next();
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If you start up your server (`deno task start`) you'll see the following:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task start deno run -A --watch=static/,routes/ dev.ts
|
||||||
|
Watcher Process started.
|
||||||
|
The manifest has been generated for 4 routes and 1 islands.
|
||||||
|
|
||||||
|
🍋 Fresh ready
|
||||||
|
Local: http://localhost:8000/
|
||||||
|
|
||||||
|
route
|
||||||
|
http://localhost:8000/
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/deserializer.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/signals.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/plugin-twind-main.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/main.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/island-counter.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/refresh.js
|
||||||
|
static
|
||||||
|
http://localhost:8000/logo.svg?__frsh_c=3c7400558fc00915df88cb181036c0dbf73ab7f5
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/alive
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-PDMKJVJ5.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-UGFDDSOV.js
|
||||||
|
internal
|
||||||
|
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-RCK7U3UF.js
|
||||||
|
```
|
||||||
|
|
||||||
|
That first `route` request is for when `Fresh` responds with the root level
|
||||||
|
`index.tsx` route. The rest, as you can see, are either `internal` or `static`
|
||||||
|
requests. You can use `ctx.destination` to filter these out if your middleware
|
||||||
|
is only supposed to deal with routes.
|
||||||
+1
-1
@@ -50,7 +50,7 @@ const toc: RawTableOfContents = {
|
|||||||
["forms", "Forms", "link:latest"],
|
["forms", "Forms", "link:latest"],
|
||||||
["islands", "Interactive islands", "link:latest"],
|
["islands", "Interactive islands", "link:latest"],
|
||||||
["static-files", "Static files", "link:latest"],
|
["static-files", "Static files", "link:latest"],
|
||||||
["middleware", "Route middleware", "link:latest"],
|
["middleware", "Route middleware", "link:canary"],
|
||||||
["error-pages", "Error pages", "link:latest"],
|
["error-pages", "Error pages", "link:latest"],
|
||||||
["routing", "Routing", "link:latest"],
|
["routing", "Routing", "link:latest"],
|
||||||
["data-fetching", "Data fetching", "link:latest"],
|
["data-fetching", "Data fetching", "link:latest"],
|
||||||
|
|||||||
+13
-2
@@ -477,6 +477,7 @@ export class ServerContext {
|
|||||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||||
const paramsAndRouteResult = paramsAndRoute(req.url);
|
const paramsAndRouteResult = paramsAndRoute(req.url);
|
||||||
|
|
||||||
|
let state: Record<string, unknown> = {};
|
||||||
const middlewareCtx: MiddlewareHandlerContext = {
|
const middlewareCtx: MiddlewareHandlerContext = {
|
||||||
next() {
|
next() {
|
||||||
const handler = handlers.shift()!;
|
const handler = handlers.shift()!;
|
||||||
@@ -496,7 +497,12 @@ export class ServerContext {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
...connInfo,
|
...connInfo,
|
||||||
state: {},
|
get state() {
|
||||||
|
return state;
|
||||||
|
},
|
||||||
|
set state(v) {
|
||||||
|
state = v;
|
||||||
|
},
|
||||||
destination: "route",
|
destination: "route",
|
||||||
params: paramsAndRouteResult.params,
|
params: paramsAndRouteResult.params,
|
||||||
};
|
};
|
||||||
@@ -514,7 +520,12 @@ export class ServerContext {
|
|||||||
|
|
||||||
const ctx = {
|
const ctx = {
|
||||||
...connInfo,
|
...connInfo,
|
||||||
state: middlewareCtx.state,
|
get state() {
|
||||||
|
return state;
|
||||||
|
},
|
||||||
|
set state(v) {
|
||||||
|
state = v;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
const { destination, handler } = inner(
|
const { destination, handler } = inner(
|
||||||
req,
|
req,
|
||||||
|
|||||||
@@ -19,3 +19,4 @@ export {
|
|||||||
default as puppeteer,
|
default as puppeteer,
|
||||||
Page,
|
Page,
|
||||||
} from "https://deno.land/x/puppeteer@16.2.0/mod.ts";
|
} from "https://deno.land/x/puppeteer@16.2.0/mod.ts";
|
||||||
|
export { DOMParser } from "https://esm.sh/linkedom@0.15.1";
|
||||||
|
|||||||
@@ -45,10 +45,13 @@ import * as $39 from "./routes/params.tsx";
|
|||||||
import * as $40 from "./routes/props/[id].tsx";
|
import * as $40 from "./routes/props/[id].tsx";
|
||||||
import * as $41 from "./routes/state-in-props/_middleware.ts";
|
import * as $41 from "./routes/state-in-props/_middleware.ts";
|
||||||
import * as $42 from "./routes/state-in-props/index.tsx";
|
import * as $42 from "./routes/state-in-props/index.tsx";
|
||||||
import * as $43 from "./routes/static.tsx";
|
import * as $43 from "./routes/state-middleware/_middleware.ts";
|
||||||
import * as $44 from "./routes/status_overwrite.tsx";
|
import * as $44 from "./routes/state-middleware/foo/_middleware.ts";
|
||||||
import * as $45 from "./routes/umlaut-äöüß.tsx";
|
import * as $45 from "./routes/state-middleware/foo/index.tsx";
|
||||||
import * as $46 from "./routes/wildcard.tsx";
|
import * as $46 from "./routes/static.tsx";
|
||||||
|
import * as $47 from "./routes/status_overwrite.tsx";
|
||||||
|
import * as $48 from "./routes/umlaut-äöüß.tsx";
|
||||||
|
import * as $49 from "./routes/wildcard.tsx";
|
||||||
import * as $$0 from "./islands/Counter.tsx";
|
import * as $$0 from "./islands/Counter.tsx";
|
||||||
import * as $$1 from "./islands/MultipleCounters.tsx";
|
import * as $$1 from "./islands/MultipleCounters.tsx";
|
||||||
import * as $$2 from "./islands/ReturningNull.tsx";
|
import * as $$2 from "./islands/ReturningNull.tsx";
|
||||||
@@ -104,10 +107,13 @@ const manifest = {
|
|||||||
"./routes/props/[id].tsx": $40,
|
"./routes/props/[id].tsx": $40,
|
||||||
"./routes/state-in-props/_middleware.ts": $41,
|
"./routes/state-in-props/_middleware.ts": $41,
|
||||||
"./routes/state-in-props/index.tsx": $42,
|
"./routes/state-in-props/index.tsx": $42,
|
||||||
"./routes/static.tsx": $43,
|
"./routes/state-middleware/_middleware.ts": $43,
|
||||||
"./routes/status_overwrite.tsx": $44,
|
"./routes/state-middleware/foo/_middleware.ts": $44,
|
||||||
"./routes/umlaut-äöüß.tsx": $45,
|
"./routes/state-middleware/foo/index.tsx": $45,
|
||||||
"./routes/wildcard.tsx": $46,
|
"./routes/static.tsx": $46,
|
||||||
|
"./routes/status_overwrite.tsx": $47,
|
||||||
|
"./routes/umlaut-äöüß.tsx": $48,
|
||||||
|
"./routes/wildcard.tsx": $49,
|
||||||
},
|
},
|
||||||
islands: {
|
islands: {
|
||||||
"./islands/Counter.tsx": $$0,
|
"./islands/Counter.tsx": $$0,
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export const handler = (_req: Request, ctx: MiddlewareHandlerContext) => {
|
||||||
|
ctx.state = { handler1: "it works" };
|
||||||
|
return ctx.next();
|
||||||
|
};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export const handler = (_req: Request, ctx: MiddlewareHandlerContext) => {
|
||||||
|
ctx.state.handler2 = "it works";
|
||||||
|
return ctx.next();
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { HandlerContext, PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export const handler = (_req: Request, ctx: HandlerContext) => {
|
||||||
|
ctx.state.handler3 = "it works";
|
||||||
|
return ctx.render();
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Page(props: PageProps) {
|
||||||
|
return <pre>{JSON.stringify(props.state,null,2)}</pre>;
|
||||||
|
}
|
||||||
+20
-1
@@ -9,7 +9,7 @@ import {
|
|||||||
import manifest from "./fixture/fresh.gen.ts";
|
import manifest from "./fixture/fresh.gen.ts";
|
||||||
import options from "./fixture/options.ts";
|
import options from "./fixture/options.ts";
|
||||||
import { BUILD_ID } from "../src/server/build_id.ts";
|
import { BUILD_ID } from "../src/server/build_id.ts";
|
||||||
import { startFreshServer, withPageName } from "./test_utils.ts";
|
import { parseHtml, startFreshServer, withPageName } from "./test_utils.ts";
|
||||||
import { assertMatch } from "https://deno.land/std@0.193.0/testing/asserts.ts";
|
import { assertMatch } from "https://deno.land/std@0.193.0/testing/asserts.ts";
|
||||||
|
|
||||||
const ctx = await ServerContext.fromManifest(manifest, options);
|
const ctx = await ServerContext.fromManifest(manifest, options);
|
||||||
@@ -563,6 +563,25 @@ Deno.test({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Deno.test({
|
||||||
|
name: "/middleware - should pass state through all middlewares",
|
||||||
|
fn: async () => {
|
||||||
|
const resp = await handler(
|
||||||
|
new Request("https://fresh.deno.dev/state-middleware/foo"),
|
||||||
|
);
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, Status.OK);
|
||||||
|
|
||||||
|
const body = await resp.text();
|
||||||
|
const doc = parseHtml(body);
|
||||||
|
assertEquals(JSON.parse(doc.querySelector("pre").textContent), {
|
||||||
|
handler1: "it works",
|
||||||
|
handler2: "it works",
|
||||||
|
handler3: "it works",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test({
|
||||||
name: "/middleware - middlewareParams",
|
name: "/middleware - middlewareParams",
|
||||||
fn: async () => {
|
fn: async () => {
|
||||||
|
|||||||
+5
-1
@@ -1,4 +1,8 @@
|
|||||||
import { delay, Page, puppeteer, TextLineStream } from "./deps.ts";
|
import { delay, DOMParser, Page, puppeteer, TextLineStream } from "./deps.ts";
|
||||||
|
|
||||||
|
export function parseHtml(input: string) {
|
||||||
|
return new DOMParser().parseFromString(input, "text/html");
|
||||||
|
}
|
||||||
|
|
||||||
export async function startFreshServer(options: Deno.CommandOptions) {
|
export async function startFreshServer(options: Deno.CommandOptions) {
|
||||||
const { serverProcess, lines, address } = await spawnServer(options);
|
const { serverProcess, lines, address } = await spawnServer(options);
|
||||||
|
|||||||
Reference in New Issue
Block a user