You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
19 Min
18 Seg

Inicio y cierre de sesión

5/11
Resources

How to implement login and logout buttons in a Next.js application?

When we think about optimizing our web application, we look for resources that facilitate both development and user experience. NextAuth is a powerful tool that not only guarantees security, but also simplifies session management. In this section, we show you how to integrate Sign In and Sign Out buttons using NextAuth into your Next.js application.

Basic Sign In and Sign Out configuration

  1. Importing methods from NextAuth: NextAuth provides easy-to-use methods for handling sessions. First, import the necessary methods. We will use signIn, signOut and the useSession hook.

    import { signIn, signOut, useSession } from 'next-auth/client';
  2. Rendering the session buttons: Inside the component that will handle the login and logout, we use useSession to check the current session state. We will show the login button if there is no active session and the logout button if the session is active.

    const [session] = useSession();
    return ( <> {!session ? ( <button onClick={() => signIn()}>Sign In</button> ) : ( <button onClick={() => signOut()}>Sign Out</button> )} </>);

Avoid 'flashing' unauthenticated content.

A common problem when handling sessions is the 'flash' of unauthenticated content, where the content changes abruptly on page load. To solve this problem, useSession provides an additional load state.

  1. Use loading state: This state informs us if the session is in the process of loading, allowing us to hide the content until the session is fully loaded.

    const [session, loading] = useSession();
    if (loading) { return null; // Renders nothing while loading}

Display user information.

Once the session is active, we can display user-specific information, such as the user's name, in a simple way.

  1. Session information: The session not only indicates whether a user is authenticated, but also stores data of interest such as the user's name.

    {session && ( <span>Welcome, {session.user.name}</span>)}

Leveraging multiple authentication options.

It's no secret that many prefer faster authentication options such as logging in with social network accounts. Implementing login through platforms like GitHub can greatly improve the user experience. We will explore this functionality in more detail in the next class.

In summary, integrating NextAuth into your Next.js application not only improves security, but also provides a smooth and efficient login and logout process. By eliminating the "flash" of unauthenticated content, we ensure a more pleasant user experience. Don't hesitate to experiment and always look for ways to improve the performance and experience of your web application!

Contributions 6

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Les comparto como se vería el código con la librería actualizada

// components/Header/TopArea.tsx

...

const LoginLogout = () => {
  const { data: session, status } = useSession() // obteniendo status
  const { t } = useTranslation(['common'])

  if (status === 'loading') return null // si esta cargando no mostrar nada

  if (!session) return <Button onClick={() => signIn()}>{t('signIn')}</Button>

  return (
    <>
      <span>{session.user?.name}</span>
      <Button onClick={() => signOut()}>{t('signOut')}</Button>
    </>
  )
}

...

Otra clase donde se avanza por fuera del curso y no se ponen recursos en el video…

El método signIn también nos permite crear logins personalizados, como se explica en este artículo

Dejo mi commit como referencia - Commit link.

Contiene las actualizaciones de la version 4 y los tags para la seccion del login.
A la descripcion de la clase le falto ser mas clara, estuve revisando los commits y no encontre uno con el proceso exacto de la clase asi que toco hacerlo a mano.

import { signOut, signIn, useSession } from "next-auth/react"
Cómo se hacen las formulas de peso molecular