How to protect routes #13610
Unanswered
theprobugmaker
asked this question in
Help
Replies: 3 comments 4 replies
-
We use cookies for authentication and check them in // src/server/auth.ts
type GetServerSidePropsWithAuth<P extends { [key: string]: any }> = (context: GetServerSidePropsContext, auth: AuthData) => Promise<{ props: P }>
export const requirePageAuth = <P extends { [key: string]: any }>(inner?: GetServerSidePropsWithAuth<P>): GetServerSideProps => {
return async (ctx) => {
const auth = getValidAuthCookie(ctx.req)
if (auth === null) {
removeAuthCookie(ctx.res)
ctx.res.writeHead(302, { Location: '/' })
ctx.res.end()
return { props: {} }
}
return inner ? inner(ctx, auth) : { props: { auth } }
}
} // pages/payments.ts
export const getServerSideProps = requirePageAuth()
export default function Payments(props) { ... } |
Beta Was this translation helpful? Give feedback.
4 replies
-
Opened a RFC for redirecting here: #14890 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was wondering, what is the best way to protect routes that needs the user to be authenticated or for example that requires the user to have the email confirmed.
In PHP applications for example we usually do that on the server side using middlewares this way we avoid the user going into places that s/he is not allowed.
In Next.JS as we are dealing with SSR and we have the client and server side in the same application we can't just create middlewares on the server side as it won't work on the client side so I was wondering, what is the best way to handle those things?
In my case I have an external API for authentication and things like that with session so the API is going to return a cookie, I saw the examples specially the
with-passport
and it works perfectly but I noticed that something isn't work properly. Theprofile
page is rendering first and them redirecting, theuseUser
hook is not behaving like a middleware to avoid the user to see the page before checking.How do you guys handle this?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions