Marving
Marving

Reputation: 89

How to get current user ID with Next JS and next-auth within an API route?

I am trying to get the current user ID to push it in the creation of a document with mongodb.

I have created a specific APi route which get the data from a form. However, I cannot use useSession to get session.user.id in an API route as I can in a basic react component. so how should I proceed to retrieve the current user ID?

This is the current code of the api/companies/create.js:

import { MongoClient } from "mongodb";
// import clientPromise from "../../../lib/mongodb";

async function handler(req, res) {
  if (req.method === "POST") {
    const { name, bio, size, location, logo, website, industry } = req.body;

    // | (bio.trim() === "")
    // BACKEND VALIDATION
    if (!name || name.trim() === "") {
      res.status(422).json({ message: "Invalid input." });
      return;
    }

    // Storing it in the database
    const newCompany = {
      name,
      size,
      bio,
      location,
      logo,
      website,
      industry,
    };

    let client;

    try {
      // const client = await clientPromise;
      client = await MongoClient.connect(process.env.MONGODB_URI);
    } catch (error) {
      res.status(500).json({ message: "Could not connect to database." });
      return;
    }

    const db = client.db("main");

    try {
      const result = await db.collection("companies").insertOne(newCompany);
      // Not sure about that line:
      // newCompany.id = result.insertedId;
    } catch (error) {
      client.close();
      res.status(500).json({ message: "Storing message failed!" });
      return;
    }

    client.close();

    res.status(201).json({ message: "Sucessfuly stored company" });
  }
}

export default handler;

Upvotes: 6

Views: 6457

Answers (1)

Zac
Zac

Reputation: 2081

This is from: https://next-auth.js.org/configuration/nextjs

This is how I get a session on the server side in API routes

import type { NextApiRequest, NextApiResponse } from 'next'
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]"

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await unstable_getServerSession(req, res, authOptions)
  // you can now use session.data

I think NextAuth ultimately wants you to use middleware to control certain API routes and pass session related data to API functionality.

Upvotes: 2

Related Questions