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
@520438276964876298! 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
@736673642158620680for 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}`,
}
}
^
@520438276964876298what
@281120856527077378describes 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/draft-preview/next-pages/src/pages/%5Bslug%5D.tsx#L74. It uses
getStaticProps
but the same principle applies.
@281120856527077378
this is awesome, thank you 🙏
Star
Discord
online
Get dedicated engineering support directly from the Payload team.