Best practice for protecting page / not letting anything run before redirect
In my app, I would like to protect a few key routes. The middleware implementation of NextAuth looks interesting but I am reluctant to swap out the strategy to 'jwt'. As such, I am protecting page by page with something as below:
---
const { status } = useSession({
required: true,
onUnauthenticated() {
signIn()
},
})
console.log("I am alive")
const { data: todos } = api.todo.getAll.useQuery();
---
However, I notice in these cases, that the page continues to run - briefly (I can see the "I am alive" being logged to the console) - before its redirected to the signin page. This feels like a security lapse to me (stuff running on the page before the page loads).
What is the best way to make it wait before running the rest of the page (essentially - not running anything unless the person is authenticated)?
9 Replies
You authorize on the server
Never, I repeat never give the green light on the client.
The default T3 template has a protectedProcedure you can use.
Thanks, getAll here on the TRPC procedure is a protected procedure. However, probably I do not understand where the authentication is happening, I feel like even with it being a protected procedure, the client is still loading more than it should?
the query and the page itself are two different things
Stack Overflow
Create T3 App Redirect inside a TRPC middleware if user is not signed
How can I trigger a redirect on the server side if a signed in user has not completed their profile page
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.session || !ctx.
i wrote this answer the other day, it lists your options and their pros and cons
this is cool, thank you. i must admit, i dont understand mst of it, I think I still struggle on the getserversideprops stuff. however, the middleware in your answer works perfectly for me 🙂
starting to think this might be a good video
I still don't get the topic
Home/src/pages/api/requireAuth.ts
Page i want to protect
/src/pages/dashboard.tsx