Next.js next-auth signIn function redirects to http://localhost:3000/api/auth/error

Kinda new to next.js. Anyway am trying to add a login functionality in my react web app using next-auth in my local environment but whenever i tap the login button, it redirect to “http://localhost:3000/api/auth/error”

It should take me to google login page where i select which account to login with.

TO start off heres the structure:

image showing structure of code

Heres my LoginPage.tsx

"use client";
import { signIn, useSession } from "next-auth/react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React from "react";

const LoginPage = () => {
  const { status } = useSession();
  const router = useRouter();

  if (status === "loading") {
    return <p>Loading...</p>;
  }
  if (status === "authenticated") {
    router.push("/")
  }

  return (
    <div className="p-4 h-[calc(100vh-9rem)] md:h-[calc(100vh-9rem)] flex items-center justify-center">
      
      {/* BOX */}
      <div className=" h-full shadow-2xl rounded-md flex flex-col md:flex-row md:h-[70%] md:w-full lg:w-[60%] 2xl:w-1/2">
        
        {/* FORM CONTAINER */}
        <div className="p-10 items-center flex flex-col gap-8 md:w-[100%]">
          <h1 className="font-bold text-xl xl:text-3xl">Welcome</h1>
          <p>Log into your account or create a new one using social buttons</p>
          
          // ISSUE IS HERE
          <button
            className="flex gap-4 p-4 ring-1 ring-[#213b5e] rounded-md"
            onClick={() => {
              signIn('google')}}
          >
            <Image
              src="/google.png"
              alt=""
              width={20}
              height={20}
              className="object-contain"
            />
            <span>Sign in with Google</span>
          </button>
          <button className="flex gap-4 p-4 ring-1 ring-[#213b5e] rounded-md"
          onClick={() => signIn("github")}>
            <Image
              src="/facebook.png"
              alt=""
              width={20}
              height={20}
              className="object-contain"
            />
            <span>Sign in with GitHub</span>
          </button>
          <p className="text-sm">
            Have a problem?
            <Link className="underline" href="/">
              {" "}
              Contact us
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;

Heres my options.ts code

import { NextAuthOptions, User, getServerSession } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import GithubProvider from "next-auth/providers/github";
import { prisma } from "./connect";

declare module "next-auth" {
  interface Session {
    user: User & {
      isAdmin: Boolean;
    };
  }
}
declare module "next-auth/jwt" {
  interface JWT {
    isAdmin: Boolean;
  }
}

export const options: NextAuthOptions = {

    debug: true,
  session: {
    strategy: "jwt",
  },
  providers: [
    GoogleProvider({
      // clientId: process.env.GOOGLE_ID as string,
      // clientSecret: process.env.GOOGLE_SECRET as string,
      clientId: process.env.GOOGLE_ID!,
      clientSecret: process.env.GOOGLE_SECRET!,
    }),

    GithubProvider({
        // clientId: process.env.GOOGLE_ID as string,
        // clientSecret: process.env.GOOGLE_SECRET as string,
        clientId: process.env.GITHUB_ID!,
        clientSecret: process.env.GITHUB_SECRET!,
      }),
  ],
  secret: "PLACE-HERE-ANY-STRING",
};

export const getAuthSession = () => getServerSession(options);

My router.ts code

import { options } from "./options";
import NextAuth from "next-auth";

const handler = NextAuth(options);

export {handler as GET, handler as POST}

Heres my .env file code

# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://myuser:mypassword@localhost:5432/mydb?schema=public"
NEXTAUTH_SECRET=This is text
NEXTAUTH_URL=https://localhost:3000
GOOGLE_ID= 977467927902-trcb4gg3reqj34b6drhjs5novnftou12.apps.googleusercontent.com
GOOGLE_SECRET= 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
GITHUB_ID=f83f7e3e91fef7d3af71
GITHUB_SECRET=81432edd1610b06fe0aec444ce8c679e26f48f07

I tried other solutions of deleteing the api folder and recreating it, adding the NEXTAUTH_URL in the env file.

I also setup the google and Github Oauth client side correctly, Authorised redirect URIs i used

http://localhost:3000/api/auth/callback/google for google then
http://localhost:3000/api/auth/callback/github for github

I am using the ;astest versions of next-auth and next.js

  • 1

    you should get an error somewhere. Try to check out the network tab in developer window iin your browser. But, from the I can see that you have an s in NEXTAUTH_URL=https://localhost:3000 that I suspect should not be there.

    – 

  • i edited the https to http. Thanks for pointing that out. But still getting the same problem sadly

    – 

The reason why you are getting Redirected is because you have not set custom auth pages as options to next-auth yet

in your options, add

export const options: NextAuthOptions = {
  providers: [...]
  pages:{
   signIn: "/custom-route-to-sign-in"
  }
  ...
}

With this Next auth will not redirect, when Authentication is not successful

also when calling signIn, make sure to add redirect : false if you do not want the page to refresh, with this response will contain the error and then you can display to user.

const response = await signIn('credentials', {
    email,
    password,
    callbackUrl: '/route-to-page-after-successful-authentication',
    redirect: false,
  });

more info on custom auth pages here,
more info on redirect:false here

Leave a Comment