Skip to content

getServerSession is null in Next.js API routes (within the app directory) #7423

@ghoshnirmalya

Description

@ghoshnirmalya

Environment

System:
  OS: macOS 13.3.1
  CPU: (8) arm64 Apple M2
  Memory: 95.55 MB / 8.00 GB
  Shell: 5.9 - /bin/zsh
Binaries:
  Node: 19.2.0 - ~/.nvm/versions/node/v19.2.0/bin/node
  Yarn: 1.22.19 - ~/.nvm/versions/node/v19.2.0/bin/yarn
  npm: 9.6.2 - ~/.nvm/versions/node/v19.2.0/bin/npm
Browsers:
  Chrome: 112.0.5615.137
  Safari: 16.4

Reproduction URL

https://github.com/ghoshnirmalya/the-fullstack-app

Describe the issue

The following code always returns null if I do console.log(session) when the code is present inside the Next.js API Routes within the app directory:

export async function GET() {
  try {
    const session = await getServerSession(authOptions);
    ..
}

You can find the relevant code here.

However, the following code from the React Server Components returns the correct data:

export default async function ProjectIndexPage() {
  const session = await getServerSession(authOptions);
  ..
  
  return (..)
}

The session in the above case is something like the following:

{
  user: {
    name: 'John Doe',
    email: 'john@doe.com',
    image: 'https://lh3.googleusercontent.com/john-doe',
    id: '12345678910'
  }
}

You can find the relevant code here.

How to reproduce

  1. Clone the repository:
    git clone git@github.com:ghoshnirmalya/the-fullstack-app.git
  2. Install the necessary dependencies:
    pnpm install
  3. Add the necessary env vars:
    DATABASE_URL='mysql://database-url'
    NEXT_PUBLIC_VERCEL_URL=127.0.0.1:3000
    NEXTAUTH_SECRET=some-secret
    NEXTAUTH_URL=http://127.0.0.1:3000
    GOOGLE_CLIENT_ID=google-client-id
    GOOGLE_CLIENT_SECRET=google-client-secret
  4. Generate the Prisma client:
    npx prisma db push && npx prisma generate
  5. Run the development server:
    pnpm run dev

Expected behavior

The session should return the correct object from the API Routes. The console.log(session) should return something like the following:

{
  user: {
    name: 'John Doe',
    email: 'john@doe.com',
    image: 'https://lh3.googleusercontent.com/john-doe',
    id: '12345678910'
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    triageUnseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions