skip to Main Content

This is my first time using next-auth and for some reason when I started my project the next day, the onClick functions in my login and logout buttons component wasn’t working. There is nothing logged to the console.

Login/Logout button code:

"use client";

import { signIn, signOut } from "next-auth/react";

async function login() {
  await signIn("credentials", { callbackUrl: "/admin" }).catch(console.error);
}

async function logout() {
  await signOut({ callbackUrl: "/" }).catch(console.error);
}

export function LoginButton() {
  return <button onClick={() => login}>Sign In</button>;
}

export function LogOutButton() {
  return <button onClick={() => logout}>Sign Out</button>;
}

Header component:

import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { LoginButton, LogOutButton } from "@/components/AccountButtons";
import { getServerSession } from "next-auth";
import Link from "next/link";

export default async function Header() {
    const session = await getServerSession(authOptions);
    let button;

    if (session) {
        button = <LogOutButton />;
    } else {
        button = <LoginButton />;
    }

    return (
        <header className="flex justify-center items-center gap-5">
            <Link href="/">Home</Link>
            {button}
            <Link href="/admin/create-form">Create Form</Link>
        </header>
    )
}

Thank you,
TwoBrake.

  • Made sure components were imported correctly.
  • Made sure that "use client"; was defined at the top of the component as onClick functions can only be ran with "use client";
  • Tried moving paths.

2

Answers


  1. The login & logout functions are not being called properly on onClick events.

    export function LoginButton() {
      return <button onClick={() => login()}>Sign In</button>;
    }
    
    export function LogOutButton() {
      return <button onClick={() => logout()}>Sign Out</button>;
    }
    
    Login or Signup to reply.
  2. It’s a small mistake in the way you’re defining the onClick handlers. You are not actually calling the login and logout functions when the buttons are clicked. Instead, you are passing references to these functions, which is why nothing happens when the buttons are clicked.

    Try this,

    "use client";
    
    import { signIn, signOut } from "next-auth/react";
    
    async function login() {
      await signIn("credentials", { callbackUrl: "/admin" }).catch(console.error);
    }
    
    async function logout() {
      await signOut({ callbackUrl: "/" }).catch(console.error);
    }
    
    export function LoginButton() {
      return <button onClick={login}>Sign In</button>; // Change here
    }
    
    export function LogOutButton() {
      return <button onClick={logout}>Sign Out</button>; // Change here
    }
    

    This way, when the button is clicked, it will call the login or logout function, respectively.

    Your Header component seems to be fine, but there’s a significant issue: you are using an async function directly in a React component without using useEffect or any other React hook to handle asynchronous operations. This could lead to unexpected behavior, especially during server-side rendering.

    Here’s a revised version using useEffect and useState, Try this one.

    import React, { useEffect, useState } from 'react';
    import { authOptions } from "@/app/api/auth/[...nextauth]/route";
    import { LoginButton, LogOutButton } from "@/components/AccountButtons";
    import { getServerSession } from "next-auth";
    import Link from "next/link";
    
    export default function Header() {
        const [session, setSession] = useState(null);
    
        useEffect(() => {
            const fetchSession = async () => {
                const sessionData = await getServerSession(authOptions);
                setSession(sessionData);
            };
    
            fetchSession();
        }, []);
    
        let button = session ? <LogOutButton /> : <LoginButton />;
    
        return (
            <header className="flex justify-center items-center gap-5">
                <Link href="/">Home</Link>
                {button}
                <Link href="/admin/create-form">Create Form</Link>
            </header>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search