1

I am trying to implement authentication using nextjs, next-auth and prisma. I can successfully signin, signout to my account although, as for the session it's not returning the session from the code in index.tsx

Index.tsx - I am logging the session object from this file and it's returning an undefined value.

import React from 'react';
import { signIn, signOut, useSession } from 'next-auth/client';

export default function index() {
  const [session, loading] = useSession();

  React.useEffect(() => {
    console.log(session); // This returns an undefined value
  }, []);

  ...

}

[...nextauth].ts - Checking if the user exists in the database and returning the user value using prisma in the authorize function.

export default NextAuth({
  providers: [
    providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        var user = null;
        await prisma.user
          .findMany({
            where: {
              email: credentials.email,
              password: credentials.password,
            },
          })
          .then((res) => {
            if (res) {
              user = res;
            }
          })
          .catch((err) => {
            throw err;
          });

        console.log(user);
        return user;
      },
    }),
  ],
  pages: {
    signIn: '/login',
  },
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,
  },
  secret: process.env.JWT_SECRET,
});

App.tsx

import { Provider } from 'next-auth/client';
import { AppProps } from 'next/app';

const App = ({ Component, pageProps }: AppProps) => {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps}></Component>
    </Provider>
  );
};

export default App;

package.json - Dependency information in my environment.

 {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
      },
      "dependencies": {
        "@prisma/client": "^2.30.3",
        "@tailwindcss/forms": "^0.3.3",
        "apollo-server-micro": "^3.3.0",
        "axios": "^0.21.3",
        "cookie": "^0.4.1",
        "graphql": "^15.5.2",
        "jsonwebtoken": "^8.5.1",
        "next": "11.1.2",
        "next-auth": "^3.29.0",
        "query-string": "^7.0.1",
        "react": "17.0.2",
        "react-dom": "17.0.2",
        "react-hook-form": "^7.15.0"
      },
      "devDependencies": {
        "@types/cookie": "^0.4.1",
        "@types/jsonwebtoken": "^8.5.5",
        "@types/node": "^16.7.10",
        "@types/react": "17.0.19",
        "autoprefixer": "^10.3.4",
        "eslint": "7.32.0",
        "eslint-config-next": "11.1.2",
        "postcss": "^8.3.6",
        "prisma": "^2.30.3",
        "tailwindcss": "^2.2.9",
        "ts-node": "^10.2.1",
        "typescript": "^4.4.2"
      }
    }

3 Answers 3

2

Your console log running while session not fully loaded. add session state to the useffect to run when it changes

    React.useEffect(() => {
        console.log(session);
       
  }, [session]); //Add session state to the useEffect
0

it'll be

const {data: session, status} = useSession()
1
  • 1
    Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. - From Review Commented Aug 22, 2022 at 9:51
0

you are using an async function. There is no need to use 'then'.

async function authorize(credentials) {
  try {
    const user = await prisma.user.findMany({
      where: {
        email: credentials.email,
        password: credentials.password,
      },
    });

    return user;
  } catch (error) {
    Promise.reject(error);
  }
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.