I’ve been using this example
https://github.com/payloadcms/next-auth-frontendto set up authentication in my app. However, this example does authentication in the client-side. For my app I’d like to do check if the user is authenticated server-side in getServerSideProps and then pass the user to the client-side, which in turn makes some other user-specific requests where needed.
However, I’m a bit lost on where to start: Simply calling
http://blabla.com/api/users/me
is obviously not possible since the server-side does not have the authentication cookies set.
What is the best strategy to achieve this?
Thanks in advance!
I think you want to use the Payload API
https://payloadcms.com/docs/local-api/overview
sorry, Local API
Hey @twoxic how are you getting on here? Like @notchr said, the local api has auth operations which make this simple and easy >
https://payloadcms.com/docs/local-api/overview#auth-operationsFor now I've chosen the simpler route and just authenticated in the frontend!
I am following in the same footsteps as Twoxic I believe, setting it up following the instructions, and then unclear on how to make an authenticated request. Is it possible to add into the repo an example of an authenticated request on a collection that isn't users?
If you want to make authenticated REST/GraphQL requests in getServerSide props, you would need to explicitly forward
req.headers.cookie
in your requests, as HTTP only are only included by default in the browser.
example given:
export const getServerSideProps = async ({req, res}) => {
const cookie = req.headers.cookie;
const user = await fetch("https://your-payload-url/api/users/me", {
method: 'GET',
cookie,
}).then(res => res.json());
return { props: { user } };
}
@alamit I believe the fetch request also needs credentials: 'include', otherwise the cookies are not automatically sent with the request, right?
Say I want to login on the frontend, setting the authentication cookie
In the browser runtime yes, in the server runtime credentials has no effect.
Ah I see!
Thanks for help guys, I think I got it working. (The error I was running into was due to my fetch request being wonky). I still have a lot to learn in regards to the authentication, and what is actually happening behind the scenes.
@markle is it possible to share your authentication stuff? I am trying to use the nextjs 13 app directory to authenticate server side too
fyi, here is how you do it in
app routes:
import { cookies } from 'next/headers'
const me = await fetch(
'http://localhost:' + process.env.PORT + '/api/users/me',
{ headers: { Cookie: cookies().toString() } }
).then((r) => r.json())
@thgh. have you used this with the app route method?
https://nextjs.org/docs/app/api-reference/functions/cookies
nice, just tested it and it works like a charm
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.