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
}
}
}