What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth.

My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoint through Postman at

http://localhost:3000/api/user/clotdcsk0001kvjmg8bvbkxy7
.

I have attempted passing a Bearer Token in the Authorization part of the request, which corresponds to the next-auth.session-token cookie. While this allows me to bypass the middleware protection and reach the endpoint, I still cannot retrieve the session object within the GET method for custom logic.

Below is an excerpt from my /api/user/[id]/route.ts file.

export async function GET ( req : NextRequest, ds : DynamicSegment ) {

   const session = await getServerSession( options )

   console.log(session) //prints null
   
   // Custom logic to handle the request...
  
} 

Interestingly, when I employ a similar approach of using the getServerSession method in a page.tsx file to obtain the session object, everything works smoothly (via the explorer). What steps am I overlooking to successfully interact with a session object when making requests from Postman?

Answer №1

After some investigation, I learned that the next step in making API requests is to include the cookie for next-auth.session-token when calling from a browser or Postman.

let response = await fetch(`/api/users/${userId}`, {
  method: "GET",
  headers: { 
    "Content-Type": "application/json",
    "Cookie": `next-auth.session-token=${sessionToken};path=/;expires=Session`    
  },
   cache: 'no-store',
});

The sessionToken mentioned above is obtained from

page.tsx

import { cookies } from 'next/headers'
   
   // ...
   
   // Accessing the sessionToken object
   const cookieStore = cookies()
   let sessionTokenCookie = cookieStore.get('next-auth.session-token')
   let sessionToken = sessionTokenCookie.value;

Answer №2

Feel free to experiment with the following code snippet:

// Utilizing NextAuth
export const handler = NextAuth(customAuthOptions);
export { handler as GET, handler as POST };

// Implementing in page.js 
import { customAuthOptions } from "../api/auth/[...nextauth]/route";

const userSession = await getServerSession(customAuthOptions);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Problem with Metadata Changes in Next.js: Metadata Getting Reset After Rebuilding .next Directory

I've run into a problem while trying to customize metadata in my Next.js app. Even though I can successfully make changes to the metadata in my layout.tsx file, these modifications are not showing up in the console output. Additionally, whenever I del ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

To combine arrays A and B within a React useState object, simply pass them as arguments when initializing the state

Currently, I am working on integrating infinite scroll functionality in React, where I need to fetch data from a backend API for loading content on the next page. The challenge I'm facing is that my state is set as an object using useState, and I need ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Error encountered when trying to access children components in Typescript, even though React.FC is being

I am facing an issue with a child component that has the following structure: interface ChildProps extends AnotherInterface{ route: string, exitAction: ActionCreatorWithoutPayload, } const ChildComponent:FC<ChildProps> = ({title, shape, rout ...

Issue with third-party react module (effector) causing Webpack error

UPDATE: After struggling with my own custom Webpack setup, I decided to switch to using react-scripts, and now everything is compiling smoothly. It seems like the issue was indeed with my Webpack/Babel configuration, but I still can't pinpoint the exa ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

Is it possible to utilize the layout of a parent route for the loading screen of a sub route?

App Structure Currently, I am working with Next JS 13 and the app router. The simplified structure of my app is as follows: app -(landing) - page.js - layout.js -(results) - layout.js - loading.js - results - page.js -components - vapour ...

Using Javascript outside of the AngularJS environment

I am trying to utilize Javascript functions outside the controller in Angular JS instead of using a service within a module. Is this allowed? For instance: var UrlPath="http://www.w3schools.com//angular//customers.php" //this section will store all the f ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

What is the best method for integrating UL / LI into JSON to HTML conversion?

Currently, I am working on converting a JSON string into HTML format. If you want to take a look at the code, here is the jsfiddle link: http://jsfiddle.net/2VwKb/4/ The specific modifications I need to make involve adding a li element around the model da ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...