skip to Main Content

I’m working on a web page that lets users Log In/Sign In and then they are redirected to a user/[id] where the id is a unique identifier they have on the database, the process to getting the user information is working fine, but when I try to redirect them back to the root / page after they have been logged out (sessions destroyed) but instead the page is reloaded but there is no user data displaying.

At first I thought this was a problem with my index page because I used a useEffect hook to redirect the user to the user/[id] page if there is an active session, but I already tested by commenting the router.push() function to prevent it from redirecting and the empty user page is still appearing after trying to log out.

The stricture of the project is the following:

src
  pages
    api
      user
        [id].ts
      logout.ts
    user
      [id].tsx
    index.tsx

My index.tsx page

import {useEffect} from 'react';
import { Button, Card, Row } from 'react-bootstrap';
import axios from 'axios';
import { useRouter } from 'next/navigation';


export default function Home() {
  const router = useRouter()
  

  useEffect(() =>{
      sessionHandler();
  },[])

    const sessionHandler = async () => {
        const session = await axios.get(`http://localhost:3000/api/session`)
        if(session.data !== null){
            router.push(`/user/${session.data.id}`)
        }
        
    }
  
  return(
      <Card className='text-center'>
          <Card.Body>
              <Card.Title>Bienvenido al sistema de Clientes de National Unity</Card.Title>
              <Card.Text>Selecciona una de las opciones para ingresar al sistema</Card.Text>
              <Row className='my-2'>
                  <Button variant='primary' onClick={() => router.push('/logIn')}>Iniciar Sesión</Button>
              </Row>
              <Row className='my-2'>
                  <Button variant='secondary' onClick={() => router.push('/signin')}>Registrarse</Button>
              </Row>
              <Row className='my-2'>
                  <Button variant='info'>Ingresar como Invitado</Button>
              </Row>
          </Card.Body>
      </Card>
  )
}

The user/[id].tsx page

import  { useState, useEffect } from "react"
import { Form, Button, Card, Row, Container, Modal } from 'react-bootstrap'
import axios from "axios"
import { useRouter, useSearchParams } from "next/navigation";
import { signOut } from "next-auth/react";

function UserPage(){
    const router = useRouter()
    const searchParams = useSearchParams()
    
    const id = searchParams.get('id');
    
    const [user, setUser] = useState({
        id: null,
        name: null,
        email: null,
    })
    
    
    const getUser = async () =>{
        
        const result = await axios.get(`http://localhost:3000/api/user/${id}`)  
            
        setUser(result.data.user)
    }

    useEffect(() =>{
        getUser()
    },[])
    const handleDestroySession = async () =>{
        const result = await axios.get('http://localhost:3000/api/logout')
    }

    //Función para log out
    const logOut = async () =>{
        await handleDestroySession()
        router.push('/');
    }


    return(
        <Container>
            <Card>
                <Card.Body>
                    <Card.Title className='mb-3'>{user.name}</Card.Title>
                    <Card.Text className='mb-3'>{user.email}</Card.Text>
                    <Button onClick={logOut}>Log Out</Button>
                </Card.Body>
            </Card> 
        </Container>   
    )
}

export default UserPage

The user session is correctly getting destroyed on the Application tab of my browser’s Dev Tools, so that is not the problem.

I have other router calls for general navigation on the project because I have other pages, and it is working fine on those, so the problem is specifically on this page.

If anyone has any idea what could be causing this issue I would appreciate the help.

2

Answers


  1. Chosen as BEST ANSWER

    I was able to find the solution. When looking at the documentation for Next-Auth I found that the SignOut method has an option to redirect to a specified url after signing out

    const logOut = async () =>{
        signOut({callbackUrl: 'http://localhost:3000'})
    }
    

    This correctly redirects to the index page of the project

    Documentation


  2. Since everything else looks good to me: try using the Next 12 router (imported from "next/router") instead of the one from "next/navigation"). The one you are using is intended for server components, so there might be some weird stuff happening, since you are using the pages structure.

    I couldn’t find much info in Vercel’s documentation, but here‘s a related question. Let me know how it goes!

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