Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Payload Auth /me not returning user

default discord avatar
pikayuhno2 years ago
10

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

  • default discord avatar
    abdullahasad72532 years ago

    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

  • default discord avatar
    pikayuhno2 years ago

    I can



    I can also do the requests from insomnia (which is like postman) and it works just fine

  • default discord avatar
    ingrid7412 years ago

    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

    null

    user where the

    payload-token

    cookie is set.

  • default discord avatar
    pikayuhno2 years ago

    Yeah they are on differenr servers



    On the request can you check if the browser sends the token in the cookie?

  • default discord avatar
    ingrid7412 years ago

    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

    PUBLIC

    prefix 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

    cookies

    library 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

    cookies

    library will just return

    undefined

    trying to get it. You're supposed to add

    credentials: include

    on 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

    user

    to 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.

  • default discord avatar
    pikayuhno2 years ago

    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}
  • default discord avatar
    abdullahasad72532 years ago

    have you added localhost:3000 in cors and csrf in payload config

  • default discord avatar
    pikayuhno2 years ago
    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 🤦

  • default discord avatar
    abdullahasad72532 years ago

    Its always the minor ones 🙂

  • default discord avatar
    ingrid7412 years ago

    🥳

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.