How to properly secure pages using app router?
Answered
Gouty oak gall posted this in #help-forum
Gouty oak gallOP
When using app router in my page.tsx files I have the following code on pages that should only be seen when logged in:
From what I can tell the page still loads and then refreshes. What is the proper way to secure those pages?
const session = await getServerSession( authOptions);
if (!session || !session.user){
redirect('/signin');
return;
}From what I can tell the page still loads and then refreshes. What is the proper way to secure those pages?
Answered by B33fb0n3
another method would be, to protect your routes via a middleware and check the auth inside the middleware. It will be executed before the page even loads and ... well.. it's secure 🙂 @Gouty oak gall
3 Replies
another method would be, to protect your routes via a middleware and check the auth inside the middleware. It will be executed before the page even loads and ... well.. it's secure 🙂 @Gouty oak gall
Answer
Gouty oak gallOP
Hmm, never really played with middleware, from a quick read seems like it could do the trick.
Is the approach I'm using a bad idea?
Is the approach I'm using a bad idea?
@Gouty oak gall Hmm, never really played with middleware, from a quick read seems like it could do the trick.
Is the approach I'm using a bad idea?
I am honest with you: I am doing nearly the same like you now. For me it’s even worse: my authprovider is clientside. Of course the the auth itself works with sessions and is completely secure, but my auth is currently handled clientside. I don’t need to secure any data. I also don’t have data that is highly private or anything like that, so it’s ok for me to do it like this.
But I don’t know your use case, so I recommend you using the middleware (must secure variant I can think of), to be on the safe side. Of course you can what you want to do
But I don’t know your use case, so I recommend you using the middleware (must secure variant I can think of), to be on the safe side. Of course you can what you want to do