T
TanStack2w ago
plain-purple

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");
}
},
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,
},
},
});
});
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?
React TanStack Start Start Basic Auth, Example | TanStack Start Docs
An example showing how to implement Start Basic Auth, in React using TanStack Start.
1 Reply
stormy-gold
stormy-gold2w ago
Actually you need to guard your server functions with an auth middleware if you do not want them to be publicly accessible.

Did you find this page helpful?