The title is rewritten to: Uncertain if Nextjs is detecting _app.js; Error: useSession must be wrapped in a <SessionProvider />
P粉771233336
2023-09-04 00:10:21
<p>I've been following some tutorials on Nextjs, Prisma and Auth0. My problem is, after trying to create a login/logout button on the header (by adding <code>import { useSession,signIn,signOut } from "next-auth/react" </code> to <code> header.js</code> file), the following error occurs in next.js<code>Error: [next-auth]: \`useSession\` must be wrapped in \<SessionProvider /></code> . I tried creating the <code>_app.js</code> file in the root folder, then at <code>/pages/_app.js</code> and finally at <code>/app/_app Created at .js</code>. None of these work. </p>
<p>This is the content of my<code>_app.js file: </code></p>
<pre class="brush:php;toolbar:false;">import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}</pre>
<p>How do I make sure Next is detecting and using it? I think the file is being ignored to some extent. </p>
<p>I tried changing the location of the <code>_app.js</code> file from the root folder of the project to <code>/pages/_app.js</code> and finally to <code> ;app/_app.js</code> . I also tried deleting the <code>.next</code> folder and re-running the server but it didn't work. </p>
<p><strong>Update 1: </strong>
Next.js version I'm using: v13.4.4</p>
<p><strong>Update 2: </strong>
I've added the <code>console.log()</code> function to the <code>_app.js</code> file and it prints to the terminal, but not on Firefox. <code>_app.js</code> Is the detection normal or is there a problem? </p>
<p><strong>I (sort of) fixed it! Check my answer below. But it doesn't work when deployed to Vercel. </strong></p>
I think I've solved this problem, I decided to forget about _app.js and put everything in my custom layout.js file. I still need to test if the user will stay logged in since header.js is outside of layout.js.
How I solved it: I added
Go to
layout.js
(the file that comes with Next.js by default) and pass the session in the parameter of the function being "exported" (the default function RootLayout is exported). Then I wrapped all return() parameters with .This is part of the code:
IMPORTANT PART: If you use the
'use client'
option, Next will not allow you to export metadata, so you need to remove export const metadata from your code = {....UPDATE: For some reason it doesn't work on Vercel (even though it runs locally). I'll try to fix it and update my answer. TL;DR: This solution works locally but does not work when deployed to Vercel.