#login page when key not exist

1 messages · Page 1 of 1 (latest)

thin wraith
#

I need the following. If the key token in the local storage is empty, the login.tsx page should be displayed and if the token is set, the dashboard.tsx page should be displayed. I would also like to know whether I have to check on all other pages whether the token is set or not. Or is it enough in the layout.tsx?

lofty pythonBOT
#

Hi @thin wraith. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, you can implement conditional routing in your Next.js application to display different pages based on the authentication state.

In your layout.tsx file, you can use a function to check if the user is logged in and then render the appropriate page. Here's an example:

import { getUser } from '@/lib/auth'
 
export default function Layout({
 dashboard,
 login,
}: {
 dashboard: React.ReactNode
 login: React.ReactNode
}) {
 const isLoggedIn = getUser() // You can modify this function to check the token in local storage
 return isLoggedIn ? dashboard : login
}

(Source: Next.js Documentation (https://nextjs.org/docs/app/building-your-application/routing/parallel-routes))

In this example, getUser() is a function that checks the authentication state. You can modify this function to check if the token in local storage is set or not.

As for checking the token on all other pages, it depends on your application's requirements. If you need to restrict access to certain pages based on the authentication state, you would need to check the token on those pages as well.

You can use the useEffect hook in combination with the useRouter hook to redirect users to the login page if they are not authenticated. Here's an example:

#
import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })
 
export default function Page() {
 const { user, loading } = useUser() // Modify useUser to check the token in local storage
 const router = useRouter()
 
 useEffect(() => {
 if (!(user || loading)) {
 router.push('/login')
 }
 }, [user, loading])
 
 return <p>Redirecting...</p>
}

(Source: Next.js Documentation (https://nextjs.org/docs/pages/api-reference/functions/use-router))

In this example, useUser() is a function that checks the authentication state. You can modify this function to check if the token in local storage is set or not. If the user is not authenticated, they are redirected to the login page.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: