Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How do I access the default ObjectId MongoDB creates with NextAuth

I'd like to push data to the MongoDB document of the user currently logged in.

From what I understand, when you sign in with Twitter (for example), Next Auth creates a new: user, account, and session for that login. And using the useSession() hook, you can access the email, image, and name of the user, but not the ObjectId that MongoDB creates for you.

That's a problem for me because I need to make requests to my server that use the _id value of the user currently logged in, for the PUT request URL. I'd like to use the _id value mongo provides you instead of adding one with something like uuid.

Is there any way to do this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I recently ran into this issue and found that using the callbacks option in [...nextauth].js allows you to modify what is sent back to the client.

Portion of my [...nextauth].js:

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    adapter: MongoDBAdapter({
      db: (await clientPromise).db("myFirstDatabase"),
    }),
    providers: [
      GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      }),
    ],
    callbacks: {
      async signIn({ user, account, profile, email, credentials }) {
        return true;
      },
      async session({ session, token, user }) {
        session.user._id = user.id;
        return session;
      },
    },
  });

The async session function will return the user object that is stored in your db, so you can add the id to the user object of session.

I can now access it using the session hook like before, but this time have access to the _id.

<div>{session.user._id}</div>

Here is a link to the NextAuth site that goes more in-depth of the power of session: NextAuth

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!