[next-auth]: `useSession` must be wrapped in a <SessionProvider /> error on the existing js file

Viewed 1920

I am adding the following code to my existing js file to validate the authentication and I am trying to follow the next-auth documentations but I am getting this error "[next-auth]: useSession must be wrapped in a SessionProvider"

I am using github credentials for the validations

my code: Working when browsing to the localhost:3000/auth/api/signin

[...nextauth.js]

import NextAuth from 'next-auth'
import GitHubProvider from 'next-auth/providers/github'
export default NextAuth({
    providers:[
        GitHubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
    ],
})

I want to put the authentication to my code written in the abc/index.js

This is my code with the next-auth and this throwing this error "[next-auth]: useSession must be wrapped in a SessionProvider"

localhost:3000/abc/index.js

import React, { Component, useMemo, useState, useEffect } from 'react';
import { useSession, SessionProvider } from 'next-auth/react';
function MyApp({ Component, pageProps }) { // i have added it here since I am not using _app.js file
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}
const abc = ({ json }) => {
  const { data: session } = useSession();
  if (session) {
    return (
      <>
        Signed in as {session.user.email} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    );
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn()}>Sign in</button>
    </>
  );
};
1 Answers

Make sure to wrap your app with the SessionProvider component in the _app.js file:

import { SessionProvider } from 'next-auth/react';

function MyApp({ Component, pageProps }) {
    return (
      <SessionProvider session={pageProps.session}>
        <Component {...pageProps} />
      </SessionProvider>
    );
  }

export default MyApp;

More info about _app.js in the Next.js docs.

Related