Trying to implement simple login but for some reason I'm not getting the user back even. I checked if the cookie is in the request headers and it is but still I'm not getting the user back.
export const getMe = async () => {
const req = await fetch('http://localhost:3000/api/users/me', {
method: 'GET',
credentials: "include",
headers: {
"Content-Type": "application/json"
}
})
if (req.status === 401) throw new Error("User not authenticated!")
const data = await req.json()
return data;
}
export const login = async (email: string, password: string) => {
const req = await fetch('http://localhost:3000/api/users/login', {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password
}),
})
if (req.status !== 200) throw new Error("There was an error!")
const data = await req.json()
return data;
}This is the code to login and get the user
Payload is not able to authenticate the jwt token in /me url you should check the admin panel in browser whether you are able to log in from there
I can
I can also do the requests from insomnia (which is like postman) and it works just fine
Are your back- and frontends on different servers? I'm facing the same issue ATM. Working on localhost too, but have masked my frontend domain to mimic the cross-site context of a multi-tenant setup (multiple frontends on various domains served by a single backend). I'm getting that
const meUserReq = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/users/me`, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
})returns a
nulluser where the
payload-tokencookie is set.
Yeah they are on differenr servers
On the request can you check if the browser sends the token in the cookie?
Nope, the token is not even on the request header of the me request in my code. But I think the fetch ran in server-side context (where the cookie isn't available) - my best guess because I wasn't able to console log anything in that context.
I was thrown off by the NEXT
PUBLICprefix on the var in the above code snippet (which is from the example/auth Next app), but that just means the var is available on client as well as server.
Anyway, I've rewritten the code to run on client instead and it works now. The example code didn't make sense where it uses the
cookieslibrary to get the cookie with the token. It's a HttpOnly cookie, which means it's not supposed to be available at all from your program, so the
cookieslibrary will just return
undefinedtrying to get it. You're supposed to add
credentials: includeon your fetch request and that'll tell the browser to put the token in your headers.
So basically you're only supposed to fetch the token when you log in, that'll add it to your session as a cookie outside your app, as well as add
userto the Auth provider inside your app so it too knows you're logged in (still refering to the examples/auth/next-app here). Then the browser will handle auth on your requests as long as you include credentials, pretty neat.
Let me know if you'd like me to share some of my code, I don't know if my thinking is correct here but it works.
it's been a while, didn't have time to code but I got back to it and I'm still facing the same issue xD
export const getMe = async () => {
const req = await fetch('http://localhost:3000/api/users/me', {
method: 'GET',
credentials: "include",
headers: {
"Content-Type": "application/json"
}
})
if (req.status === 401) throw new Error("User not authenticated!")
const data = await req.json()
return data;
}With this request I'm including the payload-token cookie but get back as response:
{"user":null}have you added localhost:3000 in cors and csrf in payload config
export default buildConfig({
serverURL: 'http://localhost:3000',
cors: ['http://localhost:5173'],
csrf: ['http://localhost:5173'],
admin: {
user: Users.slug,
bundler: webpackBundler(),
},
editor: slateEditor({}),
collections: [Users, Audit, Question, Law],
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
declare: false
},
db: mongooseAdapter({
url: process.env.DATABASE_URI,
}),
})I can't believe it, I had a spelling error 🤦
Its always the minor ones 🙂
🥳
Star
Discord
online
Get dedicated engineering support directly from the Payload team.