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

Using the useState hook will help avoid any crashes when running on IE11

I recently added a new repository to my GitHub account. The file dist/index.htm is causing Internet Explorer 11 to crash, displaying the error message: "unable to get property 'root' of undefined or null reference." This issue arises when I u ...

Displaying an STL file at the center of the screen using Three.js positioning

I need assistance with positioning a rendered STL file from Thingiverse in the center of the screen using Three.js and the THREE.STLLoader(). Currently, I have to adjust the rotation properties based on touch coordinates to get the object where I want it. ...

Convert Python strings into HTML JavaScript blocks using Jinja2

Having trouble passing a string to an HTML page in the "<script>" block. I am currently using Python, Flask, and Jinja2. Python code: def foo(): return myString #"[{title: 'Treino 7-Corrida',start: '2015-12-08',color: '#d ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

When using NextJS with Redux Persist, the HTML does not get rendered in the initial server

I am currently utilizing ReactJS/NextJS along with Redux and redux-persist, as well as Ant Design. Recently, I have noticed that my html codes and other data are not rendering in the page's source. They do render in the browser and when inspected, but ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

Having a tough time getting Storybook up and running

Hey there, I'm new to exploring React and I decided to give Storybook a try. Unfortunately, I encountered an error when attempting to run Storybook. I attempted to resolve the issue by updating with npm update, suspecting there may be dependency confl ...

What is the process for transforming binary code into a downloadable file format?

Upon receiving a binary response from the backend containing the filename and its corresponding download type, the following code snippet illustrates the data: 01 00 00 00 78 02 00 00 6c 02 00 00 91 16 a2 3d ....x...l....... 9d e3 a6 4d 8a 4b b4 38 77 bc b ...

TypeScript Library encounters issues when importing a specific data type

I recently integrated a library into my Next.js application to manage layouts using useState in react-grid-layout. To make this work with TypeScript, I had to install the necessary package shown below: npm install --save @types/react-grid-layout The code ...

Steps for verifying a new account in Firebase through Terminal Deployment

After successfully logging into an account with firebase login in a React project using VS Code, I now need to switch to another account. However, the system indicates that I am already logged in. How can I log out and sign in again? ...

Trouble persisting state with the Algolia React Instantsearch Hits component

Experimenting with Algolia React instant search, I've developed a basic component: import "./App.css"; import "bootstrap/dist/css/bootstrap.min.css"; import { Button, Offcanvas } from "react-bootstrap"; import { useState ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

Use PHP to transform an array into JSON format, then access and retrieve the JSON data using either jQuery or JavaScript

I have successfully generated JSON data using PHP: $arr = []; foreach($userinfo as $record) { $arr[] = array( 'BAid' => $record->getBAid(), 'BCid' => $record->getBCid(), 'BA ...

The issue of race condition in Node.js programming

I've been diving into the documentation, but I'm struggling to figure out what's going on here. I have two functions: one downloads a CSV file via a URL, and the next function takes that CSV file and converts it to JSON FileDownload.js co ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

How to replace text using jQuery without removing HTML tags

One of the functions in my code allows me to replace text based on an ID. Fortunately, this function is already set up and working smoothly. $('#qs_policy .questionTitle').text("This text has been updated"); However, there is another ...

Encountered an error while trying to find the Node JavaScript view

Whenever I attempt to render the URL for displaying index.js in the browser, an error arises: **Error:** Failed to locate view "index" in views directory "D:\NodeJs\Example\5expressnodjsexmp\views" Below is my application code: //Hea ...

steps for setting up babel-cli and babel-preset-react

I attempted various methods of installing babel-cli babel-preset-react Here's what I tried: npm install --save-dev babel-cli babel-preset-react However, when I run babel -h An error message appears saying The program 'babel' can be found ...

How to eliminate Image notifications in NextJS

I keep receiving a warning about the local images on my website: Image with src "http://localhost:3000/_next/static/media/icon_home.0f967506.svg" has either width or height modified, but not the other. If you use CSS to change the size of your image, also ...