TanStackT
TanStack2mo ago
1 reply
popular-magenta

Necessity of Auth Middleware

I'm following https://tanstack.com/start/latest/docs/framework/react/examples/start-basic-auth, on how to set up my own auth.
I noticed that in the example there is no auth middleware being used, particularly the fetchPosts and fetchPost functions.

We are only checking for user in _authed.tsx like this
beforeLoad: ({ context }) => {
    if (!context.user) {
      throw new Error("Not authenticated");
    }
  },

My question is, do I need to add a auth middleware like the following
export const authMiddleware = createMiddleware().server(async ({ next }) => {
  const { data: session } = await getSession({
    fetchOptions: {
      headers: getHeaders() as HeadersInit,
    },
  });
  return await next({
    context: {
      user: {
        id: session?.user?.id,
      },
    },
  });
});

Before every server call in protected pages?
An example showing how to implement Start Basic Auth, in React using TanStack Start.
React TanStack Start Start Basic Auth, Example | TanStack Start Docs
Was this page helpful?