Skip to content

How to Implement Middleware in Remix? #1432

Closed Answered by sergiodxa
goldcoders asked this question in Q&A
Discussion options

You must be logged in to vote

Instead of middleware, you can call a function directly inside the loader, this will also be more explicit. If you want to early return a response from those "middlewares" Remix let you throw the response object.

For example, if you wanted to check the user has a certain role you could create this function:

async function verifyUserRole(request: Request, expectedRole: string) {
  let user = await getAuthenticatedUser(request); // somehow get the user
  if (user.role === expectedRole) return user;
  throw json({ message: "Forbidden" }, { status: 403 });
}

And in any loader call it this way:

let loader: LoaderFunction = async ({ request }) => {
  let user = await verifyUserRole(request, "ad…

Replies: 5 comments 33 replies

Comment options

You must be logged in to vote
18 replies
@cjsauer
Comment options

@neekey
Comment options

@ZeldOcarina
Comment options

@cjsauer
Comment options

@elyobo
Comment options

Answer selected by MichaelDeBoey
Comment options

You must be logged in to vote
1 reply
@chikamichi
Comment options

Comment options

You must be logged in to vote
10 replies
@sonnguyenhong
Comment options

@sergiodxa
Comment options

@sonnguyenhong
Comment options

@sonnguyenhong
Comment options

@kiliman
Comment options

Comment options

You must be logged in to vote
3 replies
@kiliman
Comment options

@ZeldOcarina
Comment options

@silvenon
Comment options

Comment options

You must be logged in to vote
1 reply
@gustavopch
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet