title: NextJS and NextAuth session user object getting lost due to [...nextauth.ts] getting triggered to be recompiled
body: <p>I am learning NextJS and NextAuth and have implemented a Credentials sign in with my own login page and it is working where the session object contains my user model (at the moment contains everything including the password but obviously it won't stay like that).</p>
  <p>I can refresh the page and the session is maintained, however if I leave for a minute or two and then refresh the user object in my session becomes the default even though my session is not supposed to expire until next month.</p>
  <p>Below is my [...nextauth.tsx] file</p>
  <pre><code>import NextAuth, {NextAuthOptions} from 'next-auth'
  import Providers from 'next-auth/providers'
  import { PrismaClient } from '@prisma/client'
  import {session} from &quot;next-auth/client&quot;;
  
  let userAccount = null;
  
  const prisma = new PrismaClient();
  
  const providers : NextAuthOptions = {
      site: process.env.NEXTAUTH_URL,
      cookie: {
          secure: process.env.NODE_ENV &amp;&amp; process.env.NODE_ENV === 'production',
      },
      redirect: false,
      providers: [
          Providers.Credentials({
              id: 'credentials',
              name: &quot;Login&quot;,
              async authorize(credentials : any) {
                  const user = await prisma.users.findFirst({
                      where: {
                          email: credentials.email,
                          password: credentials.password
                      }
                  });
  
                  if (user !== null)
                  {
                      userAccount = user;
                      return user;
                  }
                  else {
                      return null;
                  }
              }
          })
      ],
      callbacks: {
          async signIn(user, account, profile) {
              console.log(&quot;Sign in call back&quot;);
              console.log(&quot;User Is&quot;);
              console.log(user);
              if (typeof user.userId !== typeof undefined)
              {
                  if (user.isActive === '1')
                  {
                      console.log(&quot;User credentials accepted&quot;)
                      return user;
                  }
                  else
                  {
                      return false;
                  }
              }
              else
              {
                  console.log(&quot;User id was not found so rejecting signin&quot;)
                  return false;
              }
          },
          async session(session, token) {
              //session.accessToken = token.accessToken;
              if (userAccount !== null)
              {
                  session.user = userAccount;
              }
              console.log(&quot;session callback returning&quot;);
              console.log(session);
              return session;
          },
          /*async jwt(token, user, account, profile, isNewUser) {
              console.log(&quot;JWT User&quot;);
              console.log(user);
              if (user) {
                  token.accessToken = user.token;
              }
              return token;
          }*/
      }
  }
  
  const lookupUserInDb = async (email, password) =&gt; {
      const prisma = new PrismaClient()
      console.log(&quot;Email: &quot; + email + &quot; Password: &quot; + password)
      const user = await prisma.users.findFirst({
          where: {
              email: email,
              password: password
          }
      });
      console.log(&quot;Got user&quot;);
      console.log(user);
      return user;
  }
  
  export default (req, res) =&gt; NextAuth(req, res, providers).
  </code></pre>
  <p>I trigger the signin from my custom form as below</p>
  <pre><code>signIn(&quot;credentials&quot;, {
              email, password, callbackUrl: `${window.location.origin}/admin/dashboard`, redirect: false }
          ).then(function(result){
              if (result.error !== null)
              {
                  if (result.status === 401)
                  {
                      setLoginError(&quot;Your username/password combination was incorrect. Please try again&quot;);
                  }
                  else
                  {
                      setLoginError(result.error);
                  }
              }
              else
              {
                  router.push(result.url);
              }
              console.log(&quot;Sign in response&quot;);
              console.log(result);
          });
  </code></pre>
  <p>Signin is imported from next-auth/client</p>
  <p>My _app.js is below:</p>
  <pre><code>export default function Blog({Component, pageProps}) {
      return (
          &lt;Provider session={pageProps.session}&gt;
              &lt;Component className='w-full h-full' {...pageProps} /&gt;
          &lt;/Provider&gt;
      )
  
  }
  </code></pre>
  <p>Then the page where it redirects to after signin has the below: (Not sure if this actually does anything other than fetch the active session so I can reference it from the frontend)</p>
  <pre><code>const [session, loading] = useSession()
  </code></pre>
  <p>When I signin, the callback for session in [...nextauth.tsx] returns the following:</p>
  <pre><code>session callback returning
  {
    user: {
      userId: 1,
      registeredAt: 2021-04-21T20:25:32.478Z,
      firstName: 'Some',
      lastName: 'User',
      email: 'someone@example',
      password: 'password',
      isActive: '1'
    },
    expires: '2021-05-23T17:49:22.575Z'
  }
  </code></pre>
  <p>Then for some reason the terminal that is running <code>npm run dev</code> from inside PhpStorm then outputs</p>
  <pre><code>event - build page: /api/auth/[...nextauth]
  wait  - compiling...
  event - compiled successfully
  </code></pre>
  <p>But I didn't change anything, and even if I did, surely me making a change to the app, shouldn't trigger the session to be removed, yet straight after this, the session callback then returns the following:</p>
  <pre><code>session callback returning
  {
    user: { name: null, email: 'someone@example.com', image: null },
    expires: '2021-05-23T17:49:24.840Z'
  }
  </code></pre>
  <p>So I'm a little confused, it seems like that maybe my code is working, but maybe PhpStorm is triggering recompile and then the session is cleared, but as I said above, surely making a change and the recompiled version shouldn't trigger the session to be modified.</p>
  <h2>Update</h2>
  <p>I have done a test where I did a build and started is a production version, and I can refresh the page as much as I want and the session is maintained, so I've proved that my code works fine. So it looks like it's something do with PhpStorm determining something has changed and doing a recompile even though nothing has changed.</p>