How to show log in or log out button depending on whether the user is logged in or not in next.js 14

all

I am trying to show log in or log out button depending on whether the user is logged in or not in header component.

My approach

  • in the header component i am simply checking if the session cookie exists.
  • if the cookie exits, render logout
  • if not, render login button and signup

Where is the header

  • in the root layout because it is persistent throughout the app.

problem

  • at first I had the header file be a server component to check the cookie, but the problem with that was that server components dont have a state, meaning the header will now “react” to logging in or logging out, it will just render the button depending on the first mount only

The header as a Server component :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React from 'react'
import Typography from "@mui/material/Typography";
import "./navbarHeader.css"
import Link from 'next/link';
import LogoutButton from "./logoutButton.jsx"
import { cookies } from 'next/headers';
const navbarHeader = () => {
const session = cookies().get("session")?.value;
const isAuthenticated = session? true: false;
console.log(isAuthenticated)
return (
<div className = "navbar-header">
<div className='Nav-header-buttons'>
{!isAuthenticated&&<Link className='button-28' href="/signup"> اشترك</Link>}
{!isAuthenticated&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>}
{ isAuthenticated && <LogoutButton></LogoutButton>}
</div>
<Typography variant="h1" component="h2">
<Link className='logo' href="/"><span className='red'>365</span> News</Link>
</Typography>
</div>
)
}
export default navbarHeader
</code>
<code>import React from 'react' import Typography from "@mui/material/Typography"; import "./navbarHeader.css" import Link from 'next/link'; import LogoutButton from "./logoutButton.jsx" import { cookies } from 'next/headers'; const navbarHeader = () => { const session = cookies().get("session")?.value; const isAuthenticated = session? true: false; console.log(isAuthenticated) return ( <div className = "navbar-header"> <div className='Nav-header-buttons'> {!isAuthenticated&&<Link className='button-28' href="/signup"> اشترك</Link>} {!isAuthenticated&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>} { isAuthenticated && <LogoutButton></LogoutButton>} </div> <Typography variant="h1" component="h2"> <Link className='logo' href="/"><span className='red'>365</span> News</Link> </Typography> </div> ) } export default navbarHeader </code>
import React from 'react'
import Typography from "@mui/material/Typography";
import "./navbarHeader.css"
import Link from 'next/link';
import LogoutButton from "./logoutButton.jsx"
import { cookies } from 'next/headers';
const navbarHeader = () => {
  const session = cookies().get("session")?.value;
    const isAuthenticated = session? true: false;
  console.log(isAuthenticated)
  return (
    <div className = "navbar-header">
      <div className='Nav-header-buttons'>
        {!isAuthenticated&&<Link className='button-28' href="/signup"> اشترك</Link>}
        {!isAuthenticated&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>}
        { isAuthenticated && <LogoutButton></LogoutButton>}
      </div>

        <Typography variant="h1" component="h2">
          <Link className='logo' href="/"><span className='red'>365</span> News</Link>
          </Typography>
    </div>
  )
}

export default navbarHeader
  • so, for example, if isAuthenticated was true when mounting, it will show the sign up and the log in button but not the logout. however even when pressing the log out and deleting the cookie, it wouldnt show the log out button because there’s no state, the component will not re run to check the cookie again.

so, i changed it to a client component to have a state and it worked…..for logout button, so i check the cookie, and if hit logout, the cookies gets deleted and the state changes which causes a re render and works fine

The client component Header :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"use client"
import React, { useEffect, useState } from 'react'
import Typography from "@mui/material/Typography";
import "./navbarHeader.css"
import Link from 'next/link';
import LogoutButton from "./logoutButton.jsx"
import isAuthenticated from "@/app/utils/serverActions/isAuth"
const navbarHeader = () => {
const [isAuth, setIsAuth] = useState(isAuthenticated());
useEffect(() => {
(async () => {
const isAuth = await isAuthenticated();
setIsAuth(isAuth);
})();
}, [isAuth]);
return (
<div className = "navbar-header">
<div className='Nav-header-buttons'>
{!isAuth&&<Link className='button-28' href="/signup"> اشترك</Link>}
{!isAuth&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>}
{ isAuth && <LogoutButton setIsAuth= {setIsAuth}></LogoutButton>}
</div>
<Typography variant="h1" component="h2">
<Link className='logo' href="/"><span className='red'>365</span> News</Link>
</Typography>
</div>
)
}
export default navbarHeader
</code>
<code>"use client" import React, { useEffect, useState } from 'react' import Typography from "@mui/material/Typography"; import "./navbarHeader.css" import Link from 'next/link'; import LogoutButton from "./logoutButton.jsx" import isAuthenticated from "@/app/utils/serverActions/isAuth" const navbarHeader = () => { const [isAuth, setIsAuth] = useState(isAuthenticated()); useEffect(() => { (async () => { const isAuth = await isAuthenticated(); setIsAuth(isAuth); })(); }, [isAuth]); return ( <div className = "navbar-header"> <div className='Nav-header-buttons'> {!isAuth&&<Link className='button-28' href="/signup"> اشترك</Link>} {!isAuth&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>} { isAuth && <LogoutButton setIsAuth= {setIsAuth}></LogoutButton>} </div> <Typography variant="h1" component="h2"> <Link className='logo' href="/"><span className='red'>365</span> News</Link> </Typography> </div> ) } export default navbarHeader </code>
"use client"
import React, { useEffect, useState } from 'react'
import Typography from "@mui/material/Typography";
import "./navbarHeader.css"
import Link from 'next/link';
import LogoutButton from "./logoutButton.jsx"
import isAuthenticated from "@/app/utils/serverActions/isAuth"
const navbarHeader = () => {
  const [isAuth, setIsAuth] = useState(isAuthenticated());

  useEffect(() => {
    (async () => {
      const isAuth = await isAuthenticated();
      setIsAuth(isAuth);
    })();

  }, [isAuth]);
  return (
    <div className = "navbar-header">
      <div className='Nav-header-buttons'>
        {!isAuth&&<Link className='button-28' href="/signup"> اشترك</Link>}
        {!isAuth&&<Link className='button-28' href="/login"> تسجيل الدخول</Link>}
        { isAuth && <LogoutButton setIsAuth= {setIsAuth}></LogoutButton>}
      </div>

        <Typography variant="h1" component="h2">
          <Link className='logo' href="/"><span className='red'>365</span> News</Link>
          </Typography>
    </div>
  )
}

export default navbarHeader

problems

  • first, the login route doesnt have access to the “isAuth” state in the header component, that means, while i can cause the re render by logging out because the log out is a child of header, the same cannot be done here.
  • it is slow

log in component :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
export default function Login() {
const router = useRouter()
const onSubmit = async data =>{
const bodyJson = JSON.stringify(data);
const response = await fetch('/api/users/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: bodyJson
})
if(response.ok)
router.push("/");
}
return (
<loginform>
<loginform/>
);
}
</code>
<code> export default function Login() { const router = useRouter() const onSubmit = async data =>{ const bodyJson = JSON.stringify(data); const response = await fetch('/api/users/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bodyJson }) if(response.ok) router.push("/"); } return ( <loginform> <loginform/> ); } </code>

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


  const onSubmit = async data =>{
    const bodyJson = JSON.stringify(data);
    const response = await fetch('/api/users/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: bodyJson
        })

    if(response.ok)
          router.push("/");
} 

  return (
    <loginform>
   
    <loginform/>
  );
}

the question is.

how would you go about it, how to achieve this, noting that the header is in the root layout

thank you in advance

New contributor

Alaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật