skip to Main Content

I have created an app that connects to a mongodb cluster and stores user info. The user is then able to log in with Next-Auth functionality. The app was working just fine before deploying to Vercel. On the live site I ran into some Server Config Errors. I refractored my code yet I am still running into a few errors.

I am successfully able to connect to the database for a new user sign up.

import {
  connectToDatabase,
  hashedPassword,
} from "../../helper/HelperFunctions";

const isEmpty = (value) => value.trim() === "";

const isTenChars = (value) => value.trim().length >= 10;

const emailValidation = (value) => {
  const pattern = /^[^ ]+@[^ ]+.[a-z]{2,3}$/;

  if (value.match(pattern)) {
    return true;
  } else {
    return false;
  }
};

export default async function handler(req, res) {
  if (req.method == "POST") {
    let data = req.body;

    const { firstName, lastName, email, password, userName } = data;

    const firstNameIsValid = !isEmpty(firstName);
    const lastNameisValid = !isEmpty(lastName);
    const emailIsValid = emailValidation(email);
    const passwordisValid = isTenChars(password);
    const userNameIsValid = !isEmpty(userName);

    let userDataIsValid =
      firstNameIsValid &&
      lastNameisValid &&
      emailIsValid &&
      passwordisValid &&
      userNameIsValid;

    if (!userDataIsValid) {
      return;
    }

    const client = await connectToDatabase();

    const db = client.db();

    const existingUser = await db.collection("users").findOne({ email: email });

    if (existingUser) {
      res.status(422).json({ message: "User already exists, please log in!" });
      console.log("User already exists, please log in!");
      client.close();
      return;
    }

    const protectedPassword = await hashedPassword(password);

    await db.collection("users").insertOne({
      firstName: firstName,
      lastName: lastName,
      email: email,
      password: protectedPassword,
      userName: userName,
    });

    client.close();

    res.status(201).json({ message: "Signed up!" });
  } else {
    res.status(200).json({ data: req.body });
  }
}


Here is my nextauth api route

import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

// Helper Functions
import {
  connectToDatabase,
  comparePasswords,
} from "../../../helper/HelperFunctions";

export default NextAuth({
  session: { strategy: "jwt" },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const client = await connectToDatabase();

        const userCollection = client.db().collection("users");

        const user = await userCollection.findOne({
          email: credentials.email,
        });

        if (!user) {
          client.close();

          throw new Error("No user found!");
        }

        const isValid = await comparePasswords(
          credentials.password,
          user.password
        );

        if (!isValid) {
          client.close();

          throw new Error("Invalid password");
        }

        client.close();

        if (user) {
          return {
            email: user.email,
          };
        } else {
          return null;
        }
      },
    }),
  ],
});


Before I deployed my site on Vercel, this was working just fine on localhost. The user should then proceed to a new page if the result of logging in has no errors.


const result = await signIn("credentials", {
      redirect: false,
      email: form.email,
      password: form.password,
    });

    if (!result.error) {
      console.log(true);
      router.replace("/suggestions");
    } else {
      console.log(result.error);
      setLoginResult(result.error);
    }

2

Answers


  1. If you see CLIENT_FETCH_ERROR make sure you have configured the NEXTAUTH_URL environment variable.

    when developing you set it to localhost:3000, now you need to set that to your deployed url.

    Login or Signup to reply.
  2. The problem for me was with the NEXTAUTH_URL. For some reason, other variables in the .env-local can be surrounded by quotes (" ") but the NEXTAUTH_URL CAN’T. So i just removed it an it worked. The anoying part is that you don’t see this in the terminal

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search