Reputation: 1
`I am currently working on a To-Do app to practice Next.js and Next-Auth. I am using Next-Auth for OAuth Provider and I want to add a 'createdBy' property to each to-do item with the corresponding user ID. This will allow me to fetch the to-do items for a specific user. However, I am facing issues in retrieving the details of the current user in API routes as the 'getServerSession' function is always returning null.
Here is My Next auth setup
import { authOptions } from '@/lib/auth-options'
import NextAuth from 'next-auth'
const handler = NextAuth(authOptions)
export {handler as GET,handler as POST}
Here are my authOptions
import { type NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import { getAuthCredentials } from "./secrets";
export const authOptions: NextAuthOptions = {
providers: [
GithubProvider({
clientId: getAuthCredentials().clientId,
clientSecret: getAuthCredentials().clientSecret,
}),
],
secret: getAuthCredentials().secret,
session: {
strategy: "jwt",
},
callbacks: {
jwt: ({ token, user, session }) => {
if (user) {
token.id = user.id;
}
return token;
},
session: ({ session, token }) => {
if (token?.id) {
session.user.id = token.id;
}
return session;
},
},
pages: {
signIn: "/signin",
signOut: "/signout",
},
};
In Server Components while using getServerSession(authOptions) is working fine In Client Components while using useSession() is also working fine
but in api routes it is returning null
Here is my api route handler for creating todo // api/todos
export async function POST(req: NextRequest) {
let body = await req.json();
const session = await getServerSession(authOptions);
console.log({ session });
// {session : null}
let validateBody = addTodoSchema.safeParse(body);
console.log({ validateBody });
if (!validateBody.success) {
return NextResponse.json({
success: false,
error: validateBody.error,
});
}
try {
await connectToDatabase();
let todo = await prisma.todo.create({
data: {
...body,
createdBy: session?.user.id,
},
});
return NextResponse.json({
success: true,
data: todo,
message: "Todo created successfully",
});
} catch (error: any) {
console.log({ error });
return NextResponse.json({
success: false,
error: error.message,
});
} finally {
await prisma.$disconnect();
}
}
Here is the code to making request to the above endpoint
"use server";
import { headers } from "next/headers";
export const addTodo = async ({ title }: { title: string }) => {
try {
let res = await fetch("http://localhost:3000/api/todos", {
method: "POST",
headers: headers(),
body: JSON.stringify({
title,
}),
});
let data = await res.json();
console.log({ data });
} catch (error: any) {
console.log({ error });
// throw new Error(error.message);
}
};
I am passing the title from the form when submit is clicked and in the above code i added headers() i saw it somewhere but still it is not working
i am getting this error in terminal
⨯ TypeError: Response body object should not be disturbed or locked at extractBody
can someone help me with this?
Thank You.
your text
`
Upvotes: 0
Views: 818
Reputation: 31
As described in here the problem is that the session data is stored in the cookies and cookies are only available when the request is made from browser, so if you ever upgrade then you'll have to make the requests from components
Upvotes: 0
Reputation: 1
I had a same problem, I downgraded to 13.5.2 now its working fine for me.
Upvotes: 0