Route Guarding with nextjs

How do you implement route guarding with nextjs? Not too sure what would be the recommended way to do it. Basically what I is use a context provider then “useeffect“ my way into route guarding Context: Firebase for backend and auth
6 Replies
Neto
Neto2y ago
middleware or something like get server side props
matdexir
matdexirOP2y ago
Can you show me a minimal example?
Glenn
Glenn2y ago
I did it with getServerSideProps as well, will send in an example asap
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getServerAuthSession(context);
if (!session) {
return {
redirect: {
destination: "/auth/signin",
},
};
}

if (!session.user.configured) {
return {
redirect: {
destination: "/app/getting-started",
},
};
}

return { props: {} };
}
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getServerAuthSession(context);
if (!session) {
return {
redirect: {
destination: "/auth/signin",
},
};
}

if (!session.user.configured) {
return {
redirect: {
destination: "/app/getting-started",
},
};
}

return { props: {} };
}
Dunno if that's the right way to do it But it works
matdexir
matdexirOP2y ago
Thanks for sharing! Where should I put this? Also does it route guard any of the possible paths? Ex: say I have path /A, /B, /Login. My expectations would be that if you go to /A or /B you get redirected to /Login and also if you go to /doesnotexist you also get redirected to /Login
Glenn
Glenn2y ago
Same file as the Page Components you create Just like you do it all the time with getServerSideProps
matdexir
matdexirOP2y ago
Want results from more Discord servers?
Add your server