Search code examples
next.jsnext-auth

NextAuth Window is Not Defined Server LogIn Call


I have a event flow where a user registers an account, which triggers a POST API request that creates a record in my DB and then should call Next-auth signIn() to create the session and redirect the user to the /app/feed page. However, since this signIn() is made with the NextJS API route it is made on the server side, which is why I believe I am receiving the following error.

error - ReferenceError: window is not defined
at _callee5$ (/Users/user/dev/nextjs/nextjs-with-nextauth/node_modules/next-auth/react/index.js:330:13)

Is there a way to create a session from signIn() on the server-side? Is there a better flow I am not considering to create the session after the user is created?

Code:

import prisma from "@/libs/client";
import { signIn } from "next-auth/react";

export default async function handler(req, res) {
  console.log(req.method);
  console.log(req.body);
  if (req.method === "POST") {
    if (
      req.body.email &&
      req.body.password &&
      req.body.confirmPassword
      //   req.body.tos
    ) {
      if (req.body.password == req.body.confirmPassword) {
        const registeredUser = await prisma.appUsers.create({
          data: {
            email: req.body.email,
            password: req.body.password,
          },
        });
        console.log(`Registered User: ${JSON.stringify(registeredUser)}`);
        await signIn("credentials", {
          callbackUrl: "/app/feed",
          email: registeredUser.email,
          password: registeredUser.password,
        });
      } else {
        return "Password does not match.";
      }
    } else {
      return "Form not filled in completely.";
    }
  } else {
    return null;
  }
}

Solution

  • As it is clear in docs :

    signIn()

    . Client Side: Yes
    . Server Side: No

    The signIn() method should be called from the client side so here, since you don't want to make your function running on the client, one solution is to not call signIn() inside it, but instead, make it return registeredUser .
    And from the client side you call your handler function to get the registred user then use the signIn() method to sign in