Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/start/framework/react/guide/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,28 @@ const loggingMiddleware = createMiddleware().server(async ({ next }) => {
})
```

The exception to always returning `next()` is throwing errors. By default, throwing an error will cause the router to short-circuit and return the data passed into the `Error` as a 500 HTTP error-code response. If you want to return another error code, like with an authentication middleware, you can throw the `json` helper.

```tsx
import { createMiddleware, json } from "@tanstack/react-start";

const authMiddleware = createMiddleware().server(async ({ next, request }) => {
const client = await getMyDb();
if (!client) {
throw new Error("Oh No!"); // returns a 500 HTTP response to the client
}
const sessionCookie = request.headers.get("Authorization");
const user = await client.getUser(sessionCookie);
if (!user) {
throw json({
message: "you shall not pass!"
}, {status: 401})
}

return await next({ context: { user }}) // pass the user's information to the next middlware or server function
})
```

## Request Middleware

Request middleware is used to customize the behavior of any server request that passes through it, including server routes, SSR and server functions.
Expand Down