[SOLVED] Issue with Authentication API, Next.js and React: GET Works, PUT/POST Fail

Iā€™m developing a dApp with Next.js, React, and the Authentication API of Moralis with NextAuth and Metamask.

I am facing the following problem: The user session only seems to be accessible during GET requests on my backend. However, for other types of requests such as PUT or POST, the session is not found, even though as I see the session cookies are present in the request.

The authentication with Metamask and the session establishment process are working correctly. I have successfully implemented an endpoint in my backend that handles GET requests and accesses session data without any issues. However, I encounter an obstacle when working with other types of requests. In a specific endpoint, where I need to receive data and prefer to use POST or PUT methods, the system fails to find the session, even though the session cookies are present in the request. I am seeking advice or suggestions to solve this specific problem related to handling sessions in requests that are not of the GET type.

**Code in '/api/auth/[...nextauth].ts':**
import NextAuth from 'next-auth';
import { MoralisNextAuthProvider } from '@moralisweb3/next';
export default NextAuth({
  providers: [MoralisNextAuthProvider()],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.user = user as User;
      }
      return token;
    },
    async session({ session, token }) {z
      if (token.user) {
        session.user = token.user;

      }

      return session;
    },
  },
});
**// Service to get user information with session address   -- Ok - Correct**
export const getUserData = async () => {
  const response = await fetch('http://localhost:3000/api/profile', {
    method: 'GET',
    credentials: 'include', // Para incluir cookies en la solicitud
  });
  if (!response.ok) {
    throw new Error(`Error: ${response.status}`);
  }
  return await response.json();
};
**// Service to update contact information of the profile -- 401 unauthorized - Error**
export const updateContactInfo = async (contactInfo: ContactInfo) => {
  const response = await fetch('http://localhost:3000/api/profile/contact-info', {
	method: 'PUT',
	credentials: 'include',
	headers: {
	  'Content-Type': 'application/json',
	},
	body: JSON.stringify(contactInfo),
  });
  if (!response.ok) {
	throw new Error(`Error: ${response.status}`);
  }

Hi there, I believe next-auth has its own way of how to handle the session in your api routes

I believe you must use their own functions to get it working
You can have a look at this guide that they posted on how to get the session on the server/api routes

https://next-auth.js.org/configuration/nextjs#getserversession

https://next-auth.js.org/configuration/nextjs#in-api-routes

After doing some research, I found finally the solution.

On endpoints with POST or PUT requests, the body of the request must be treated as follows:

const body = {...req.body} ;
req.body = null ;
const session = await getSession({ req:req });
req.body = body ;
1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.