The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here?

Objective: My goal is to fetch session information in the getServerSideProps (while ensuring it's a protected route that redirects unauthenticated users to the homepage). Once I have the session data, I intend to log it so I can proceed with my code and pass it down to the components.

dashboard.tsx

import Details from '@/sections/Dashboard/Details';
import LatestCampaigns from '@/sections/Dashboard/LatestCampaigns';
import Footer from '@/sections/Footer';
import Navbar from '@/sections/Navbar'
import { GetServerSideProps } from 'next';
import { Session } from 'next-auth';
import { getSession } from 'next-auth/react';
import React from 'react';

export interface Props {
  session: Session | null
}

const Dashboard = ({ session }: Props) => {
  console.log(`Dashboard: ${session}`);
  console.info(session);

  return (
    <>
      <Navbar />
      <Details />
      <main>
        <LatestCampaigns />
        <Footer />
      </main>
    </>
  )
}

export default Dashboard;

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const _sess = await getSession(context);

  console.log('Checking..');
  console.info(_sess);

  if (!_sess) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session: _sess
    }
  }
}

I've also attempted passing the session down directly without using a variable.

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const session = await getSession(context);

  console.log('Checking..');
  console.info(session );

  if (!session ) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session
    }
  }
}

Answer №1

It is recommended to utilize getServerSession in the context of getServerSideProps. The usage of getSession() is specifically advised for client-side operations, as outlined in the NextAuth.js documentation:

The getSession() helper provided by NextAuth.js should only be invoked client-side to retrieve the current active session.

To demonstrate the implementation of getServerSession, consider the following example:

// [...nextauth].ts

import NextAuth from 'next-auth'
import type { NextAuthOptions } from 'next-auth'

export const authOptions: NextAuthOptions = {
  // your configurations
}

export default NextAuth(authOptions);
import { authOptions } from 'pages/api/auth/[...nextauth]'
import { getServerSession } from "next-auth/next"

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const session = await getServerSession(context.req, context.res, authOptions);

  console.log(session);

  if (!session ) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session
    }
  }
}

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

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

Set the datepicker to automatically show today's date as the default selection

The date picker field is functioning correctly. I just need to adjust it to automatically display today's date by default instead of 1/1/0001. @Html.TextBoxFor(model => model.SelectedDate, new { @class = "jquery_datepicker", @Value = Model.Selecte ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

"Implementing constraints in Postgres using Node.js

Currently, I am struggling with writing a constraint code to handle situations where a user tries to search for an id that does not exist in the database (specifically PostgreSQL). Despite my efforts, the if statement in the code below does not seem to be ...

Encountering difficulty in identifying the error during data fetching on the server side of a Next.js application

I am attempting to troubleshoot an error with my Next.js server-side data fetching, but I am encountering two problems. export async function getStaticProps() { try { const fetchUrl = "some api url"; const resp = await axios.get(fetchUrl); ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Basic HTML and JavaScript shell game concept

After spending several days working on this project, I am struggling to understand why the winning or losing message is not being displayed. The project involves a simple shell game created using HTML, JavaScript, and CSS. I have tried reworking the JavaSc ...

Challenge with sending CSV file as attachment on response in Express not resolving

Hey there, I've been facing an issue with sending a response from a post request that includes downloading an attachment. Although the response is correct, I don't see any download or save-as pop-up. I have verified that the headers are set corre ...

Array-based input validation

Is there a way to validate an input field against a list of strings in an array without using custom directives or patterns? For example, if the array contains town, city, and house, then typing any of those words should result in a validation failure. An ...

Error TS2339: The 'getOoxml' property is not found within the 'Worksheet' type

Running on node version 20.12.0 "react": "^18.2.0" I created a React application using the Yo Man generator for Office version 5.0.0. The code in the file looks like this: async function getExcelOOXML() { try { await Excel ...

The deprecated body parser is throwing an error due to the lack of the extended option

I am encountering an issue with my code and I'm not sure how to resolve it. Since I am new to the codebase, I feel completely lost and clueless about what steps to take. body-parser deprecated undefined extended: provide extended option index.js:20:2 ...

Sending data via an AJAX POST request in the request parameter

I have a question regarding the method of making a POST request in my code: $.ajax({ url :"/clientCredentials.json", type: "POST", data: { "clientEmail": email, "clientName":clientName, "orgName":orgName, "l ...

What is the best way to position this dropdown menu component directly under a specific section of my navbar in a React application?

As I delved into creating a basic navbar and dropdown menu in React, I encountered a puzzling issue. I envisioned a section within the nav that would trigger a dropdown menu right below it upon hovering over it. Attempting to replicate this functionality b ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

Connect the Vue component to the Vue instance

I am currently working with a Vue component that looks like this: Vue.component('number-input', { props: {}, template: `<textarea class="handsontableInput subtxt area-custom text-center text-bold" v-model="displayValue" @blur="isInput ...

What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue: I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication ...

What is the best approach for determining the most effective method for invoking a handler function in React?

As a newcomer to React, I am navigating through the various ways to define callback functions. // Approach 1 private handleInputChange = (event) => { this.setState({name: event.target.value}); } // Approach 2 private handleInputChange(event){ t ...