Search code examples
reactjssessionnext.jsnext-auth

Can't access session in NextJS/NextAuth AppRouter


I have installed my NextJS application and after that i have followed the tutorial of NextAuth via different videos etc. Right now I have an almost working application but I can't get the getServerSession work.

I have /app/page.js:

import { getServerSession } from 'next-auth';

export default async function Home() {

  const session = await getServerSession();
  console.log(session);

  return (
    <>
    <Header />
      <main className="main-content h-screen bg-slate-50">
        <div className="container mx-auto flex justify-between items-center">
          <h1>Title</h1>
        </div>
      </main>
    </>
  )
}

But nothing is being logged. How is that possible while there is a session. This is my /app/api/auth/[...nextauth]/route.js:

import { signIn } from "@/services/auth";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

const handler = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        if (credentials == null) {
            return null;
        }
        try {
            const { user, jwt } = await signIn({
                email: credentials.email,
                password: credentials.password
            });
            return {  ...user, jwt };
        } catch (error) {
            return null;
        }
    }
    }),
  ],
  callbacks: {
    session: async({ session, token }) => {
        session.id = token.id;
        session.jwt = token.jwt;
        return Promise.resolve(session);
    },
    jwt: async ({ token, user }) => {
        const isSignIn = user ? true : false;
        if (isSignIn) {
            token.id = user.id;
            token.jwt = user.jwt;
        }
        return Promise.resolve(token);
    }
    },
    pages: {
        signIn: '/login'
    }
});

export { handler as GET, handler as POST };

And I do receive the user and jwt in the authorize function.

EDIT:


import { getServerSession } from 'next-auth';
import { authOptions } from './lib/nextAuth';

//API
import setupAxios from '@/services/AxiosSetup';

//Components
import Header from './components/header/Header';
import Greeting from "./components/greeting/Greeting";

export default async function Home() {
  const session = await getServerSession(authOptions);

  return (
    <>
    <Header />
      <main className="main-content h-screen bg-slate-50">
        <div className="container mx-auto flex justify-between items-center">
          <Greeting user={session ? session.user.email : ''} />
        </div>
      </main>
    </>
  )
}

My AxiosSetup:

import axios from 'axios';
import { getServerSession } from 'next-auth';
import { authOptions } from '../lib/nextAuth';

const strapiUrl = 'https://myapi.nl';

const setupAxios = async () => {
  const session = await getServerSession(authOptions);
  const instance = axios.create({
    baseURL: strapiUrl,
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (session.jwt) {
    const token = session.jwt;
    instance.interceptors.request.use(
      (config) => {
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  return instance;
};

export default setupAxios;

Solution

  • you have to pass authOptions. you can read How do I use next auth getServerSession in next js 13 beta server component in app directory to find about authOptions. then:

    import { notFound } from 'next/navigation'
    
    import { authOptions } from '@/path'
    
    const session = await getServerSession(authOptions)
    if (!session) notFound()