Protecting routes with getServerSideProps #16724
Replies: 2 comments
-
It should be totally fine to do this: export async function getServerSideProps(ctx: ApiRoutesTypes) {
const cookie = parseCookies(ctx);
if (!testCookie.autho) {
ctx.res.writeHead(302, { Location: redirectTo });
ctx.res.end();
return { props: { redirectLogin } };
}
// [...]
} |
Beta Was this translation helpful? Give feedback.
-
Hi, I've been scratching my head on private page securing for a while. Using
To sum it up, it can lead to a lot of unexpected complexity when you are trying to implement your auth workflow. Half of our frontend technical debt at Aplines is related to this pattern. It lead us to conclude that using Instead, we will consider all pages as public in the Next app (at least the empty shell of the page), but put a reverse proxy or a gateway in front of the actual private pages. We deport complexity of token checking etc. to technologies that are a better fit.You could also use a custom server in Next until better support for this usage is added to the framework. |
Beta Was this translation helpful? Give feedback.
-
So, I have been trying a few ways to protect a route when a user is not authenticated but so far I've been struggling with it.
The most recurring problem when trying to authenticate from getServerSideProps was that I'd often encounter a
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
, so I've been trying to not redirect from there and set aredirect
boolean so I can redirect from the client. Problem is that now I get a error that statesNo router instance found. you should only use "next/router" inside the client side of your app.
even though I'm (I think) in the client.Is it possible to solve this? If not, what would be the best approach to redirect if all my pages do heavy use of getServerSideProps but also need to be authenticated?
Beta Was this translation helpful? Give feedback.
All reactions