Replies: 1 comment 2 replies
-
|
When you want to return a value from middleware, I think using the context is the best approach. // app/context.ts
import { createContext } from "react-router"
export const authContext = createContext<{ isJWTValid: boolean }>({ isJWTValid: false })// app/route/home.tsx
import { useEffect } from "react"
import { data, useFetcher } from "react-router"
import type { Route } from "./+types/home"
import { authContext } from "~/context"
const authMiddleware: Route.MiddlewareFunction = ({ request, context }) => {
const isValid = checkSomehow(request)
context.set(authContext, { isJWTValid: isValid })
}
export const middleware: Route.MiddlewareFunction[] = [
authMiddleware,
];
export function action({ context }: Route.ActionArgs) {
const result = context.get(authContext)
return data({ success: result.isJWTValid })
}
export default function Home() {
const fetcher = useFetcher()
const handleClick = () => {
fetcher.submit(null, { method: "POST" })
}
useEffect(() => {
console.log(fetcher.data)
}, [ fetcher.data ])
return (
<div className="text-center p-4">
<button
className="text-white bg-blue-400 px-4 py-1 rounded-sm"
type="button"
onClick={handleClick}
>
Submit
</button>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone! I'm encountering challenges with handling 401 responses from
useFetcher.submitwhen implementing authentication through SSR middleware. I'd appreciate any insights or experiences you might have with similar situations.Problem Summary
I'm facing difficulties with middleware-returned responses not being properly handled by
useFetcher.submit, particularly:useFetcher.submitCurrent Architecture
Authentication Setup:
/auth/refresh), making server-side refresh impossibleAuthentication Flow:
The diagram above illustrates our current authentication flow and the issues we're encountering.
flowchart TD A[Client Request] --> B{Request Type} B -->|GET| C[Auth Middleware Check] B -->|POST/PUT| D[Auth Middleware Check] C --> E{JWT Valid?} D --> F{JWT Valid?} E -->|Yes| G[Proceed to Loader] E -->|No| H[Redirect to /auth/refresh] F -->|Yes| I[Proceed to Action] F -->|No| J[Return Structured Response] H --> K[Refresh Token Available] K --> L[Backend Refresh Request] L --> M[Redirect to Original Request] J --> N{Response Status} N -->|401 Status Code| O[Error Boundary Triggered] N -->|200 Status Code| P[Turbo-stream Parse Error] style O fill:#ffcccc style P fill:#ffcccc style H fill:#ccffcc style M fill:#ccffccPrevious Working Solution
Before migrating to middleware, I implemented a working solution using higher-order functions:
For Loaders/Actions:
authLoader/authActionHOFs/auth/refresh) → token refresh → redirect to original request{success: boolean; status: StatusCode; data: unknown}useAuthFetcherwrapper that handled client-side token refresh for POST requestsMigration Issues with Middleware
Current Implementation:
root.tsxwith protected routes configurationExpected vs Actual Behavior:
useFetcher().datareceives middleware response dataQuestions for the Community
Middleware Response Handling: Is there a recommended pattern for handling structured responses from middleware that
useFetchercan properly consume?Authentication Patterns: How do others handle similar JWT refresh token flows with path-restricted cookies in React Router v7?
Turbo-stream Compatibility: What's the correct way to return structured data from middleware that's compatible with single fetch and turbo-stream parsing?
Any guidance, examples, or alternative approaches would be greatly appreciated. Thank you for your time and insights!
Technical Details:
Beta Was this translation helpful? Give feedback.
All reactions