getServerSession in api route
Unanswered
Atlantic salmon posted this in #help-forum
Atlantic salmonOP
Hi everyone,
I'm building this small personal project using next-auth.js and mongoDB with mongoose. I try to access the session token to retrieve the user.email.. I've tried this approche but it's gives me a session null. Any idea what i'm doing wrong ?
I'm building this small personal project using next-auth.js and mongoDB with mongoose. I try to access the session token to retrieve the user.email.. I've tried this approche but it's gives me a session null. Any idea what i'm doing wrong ?
import Demande from "@/app/(models)/userDemande";
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { options } from "../auth/[...nextauth]/options";
export async function POST(req, res) {
try {
const body = await req.json();
const demandeData = body.formData;
const postDemandeData = await Demande.create({ ...demandeData });
return NextResponse.json({ demandeData }, { status: 201 });
} catch (err) {
console.error("Error in POST: ", err);
return NextResponse.json(
{ message: "Server Error", err: err.message },
{ status: 500 }
);
}
}
export async function GET(req) {
try {
// This is the part not working
const session = await getServerSession(options);
console.log("session", session);
const allDemandes = await Demande.find({ email: session?.user?.email });
console.log("allDemandes", allDemandes);
return NextResponse.json({ allDemandes }, { status: 200 });
} catch (error) {
return NextResponse.json({
message: " Demande GET failed",
error: error.message,
});
}
}