Started using Payload with Next.js and i'm interested in implementing an auth guard during SSR that makes a request to the
/api/users/me
endpoint from within
getServerSideProps
to verify if the user is authenticated or else they will get redirected.
Would something like this work?
export async function getServerSideProps(context: GetServerSidePropsContext) {
const res = await fetch("http://localhost:8080/api/users/me", {
credentials: "include",
});
const { user, errors } = await res.json();
if (!user) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: {
user: user,
},
};
}
Hi @Thinh Nguyen ! I don't think any kind of SSR will work for this, because this code won't run in the user's browser. It will run in the server, so the authentication cookies will not be present to be validated. Therefore, your code will always return a redirect to "/"
Thanks @arielarial for making this distinction clear!
I know in the app folder you can get the cookies off the request, and then you can make that same
/me
fetch with:
// you will need to get cookies from req (Context?) and then look for the payload-token cookie
fetch("http://localhost:8080/api/users/me", {
headers: {
Authorization: `JWT ${jwt from cookie on req}`,
}
}
^ @Thinh Nguyen what @Jarrod describes is the right pattern here. You just need to manually inject the token into the
Authorization
header within your server-side request. There's a demonstration of this in our official preview example, check it out
https://github.com/payloadcms/payload/blob/master/examples/preview/nextjs/pages/%5Bslug%5D.tsx#L74. It uses
getStaticProps
but the same principle applies.
@jacobsfletch @Jarrod this is awesome, thank you 🙏