nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.76k stars 3.49k forks source link

Accessing session in backend (nodeJS) #8061

Closed dawudarif closed 1 year ago

dawudarif commented 1 year ago

Question 💬

I am able to perform authentication correctly on frontend. But when i want to validate the user on the backend getSession returns null.

When i console log the session in callbacks i get an object as it should but when i do it in the backend it gives me null.

How to reproduce ☕️

This is the server side code

const { startStandaloneServer } = require('@apollo/server/standalone');
const { typeDefs } = require('./schema/typeDefs');
const { resolvers } = require('./schema/resolvers');
const cors = require('cors');
require('dotenv').config();
const { mongoose } = require('mongoose');
const express = require('express');
const colors = require('colors');
const connectDB = require('./config/db');
const path = require('path');
const { getSession, getServerSession } = require('next-auth/react');
const { log } = require('console');
const { getToken } = require('next-auth/jwt');

const corsOptions = {
  credentials: true,
  origin: 'http://locathost:3000', // Replace with the origin of your application
};

const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors(corsOptions));

const server = new ApolloServer({
  typeDefs,
  resolvers,
  // introspection: true,
  // introspection: process.env.NODE_ENV !== 'production',
  playground: {
    settings: {
      'request.credentials': 'include',
    },
  },
});

const main = async () => {
  await connectDB();

  const { url } = await startStandaloneServer(server, {
    listen: { port: PORT },
    context: async ({ req }) => {
      const session = await getSession(req);

      console.log(req.headers.cookie);
      // const session = await res.json();

      console.log('session: ' + session);

      return { session };
    },
  });

  console.log(`🚀 Server ready at: ${url}graphql`);
};

main();

and this is my config file


import prisma from '../../../../libs/prismadb';
import { PrismaAdapter } from '@auth/prisma-adapter';
import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import GithubProvider from 'next-auth/providers/github';
import bcrypt from 'bcrypt';

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'text', placeholder: 'John Appleseed' },
        password: { label: 'Password', type: 'password' },
        username: {
          label: 'Username',
          type: 'text',
          placeholder: 'John Smith',
        },
      },
      async authorize(credentials) {

        if (!credentials.email || !credentials.password) {
          throw new Error('Please enter an email and password');
        }

        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
        });

        if (!user || !user?.hashedPassword) {
          throw new Error('No user found');
        }

        const passwordMatch = await bcrypt.compare(
          credentials.password,
          user.hashedPassword
        );

        if (!passwordMatch) {
          throw new Error('Incorrect password');
        }

        return user;
      },
    }),
  ],
  callbacks: {
    async session({ session, token, user }) {
      return session;
    },
    async jwt({ token }) {
      return token;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: 'jwt',
  },
  debug: process.env.NODE_ENV === 'development',
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };```

### Contributing 🙌🏽

No, I am afraid I cannot help regarding this
balazsorban44 commented 1 year ago

We recommend using the getServerSession method on the server. See https://next-auth.js.org/configuration/nextjs#getserversession

Hard to tell more without a reproduction