If the react-cookie library is not removing cookies in production, there could be several reasons behind it. One common reason is that cookies are set with specific properties such as domain, path, secure, or sameSite, which might restrict their removal. Here are some steps to troubleshoot and solve this issue:
Step 1: Check and Set Cookie Attributes
When setting cookies with secure or sameSite attributes or specifying a path and domain, ensure you're respecting those attributes when removing the cookies.
Step 2: Create a Utility Function to Set and Remove Cookies
You can create utility functions to handle setting and removing cookies, ensuring that the same attributes are respected. Here’s an example:
import { Cookies } from "react-cookie"
// Create a cookies instance
const cookies = new Cookies()
// Function to set cookies
const setCookie = (name, value, options = {}) => {
const defaultOptions = {
path: "/",
// Include other options like domain, secure, sameSite if needed
}
cookies.set(name, value, { ...defaultOptions, ...options })
}
// Function to remove cookies
const removeCookie = (name, options = {}) => {
const defaultOptions = {
path: "/",
// Include other options like domain if needed
}
cookies.remove(name, { ...defaultOptions, ...options })
}
export { setCookie, removeCookie }
Step 3: Use the Utility Functions in Your AuthProvider
Use the setCookie and removeCookie functions in your AuthProvider component:
import React, { ReactNode, createContext, useContext, useState } from "react"
import { UserType } from "../types/user.type"
import { setCookie, removeCookie } from "../../utils/cookie.utils" // Adjust the path as needed
type AuthContextType = {
user: UserType | null
login: (userData: UserType) => void
logout: () => void
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
type AuthProviderProps = {
children: ReactNode
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [user, setUser] = useState<UserType | null>(null)
const login = (userData: UserType) => {
setUser(userData)
localStorage.setItem("currentUser", JSON.stringify(userData))
setCookie("accessToken", userData.accessToken)
setCookie("refreshToken", userData.refreshToken)
}
const logout = () => {
setUser(null)
localStorage.removeItem("currentUser")
removeCookie("accessToken")
removeCookie("refreshToken")
}
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext)
if (!context) {
throw new Error("useAuth must be used within an AuthProvider")
}
return context
}
Step 4: Verify Proper Usage in Your Navigation Component
Ensure that the useAuth hook and the AuthProvider are correctly used in your Navigation component and rest of the application.
import React, { useState, useEffect, CSSProperties } from "react"
import { useModal } from "../modal"
import { MdOutlineShortText } from "react-icons/md"
import { NavLink, useNavigate } from "react-router-dom"
import { HashLink } from "react-router-hash-link"
import { IoMailOutline } from "react-icons/io5"
import { Button } from "../button/button.component"
import { useTranslation } from "react-i18next"
import { PopupOpener } from "../popup/popup-opener.provider"
import { Menu, MenuItem } from "../menu"
import { UserSignInComponent } from "../../module/user-sign-in/user-sign-in.component"
import { useAuth } from "../../context/auth.context"
import { Icon } from "../icon/icon.component"
import logo from "../../../public/images/logo.png"
import styles from "./navigation.module.css"
import { Config } from "../../utils/config"
import { useEngineerProfile } from "../../hooks/use-user.hook"
export function Navigation({ style }: { style?: CSSProperties }) {
const { t: translate } = useTranslation()
const modal = useModal()
const { user, logout } = useAuth()
const navigate = useNavigate()
const accountProfile = useEngineerProfile()
const [activeLang, setActiveLang] = useState([false, false])
const [isOpen, setOpen] = useState(false)
const [currentUser, setCurrentUser] = useState<UserType | null>(user)
const [isDrawerOpen, setIsDrawerOpen] = useState(false)
const [isMobile, setIsMobile] = useState(window.innerWidth < 1120)
useEffect(() => {
const savedLanguage = localStorage.getItem("language")
if (savedLanguage) {
i18n.changeLanguage(savedLanguage)
if (savedLanguage === "jp") {
setActiveLang([true, false])
} else if (savedLanguage === "en") {
setActiveLang([false, true])
}
} else {
handleJp()
}
function handleResize() {
setIsMobile(window.innerWidth < 1120)
}
window.addEventListener("resize", handleResize)
return () => window.removeEventListener("resize", handleResize)
}, [])
useEffect(() => {
const currentUser = localStorage.getItem("currentUser")
if (!currentUser) return
setCurrentUser(JSON.parse(currentUser))
}, [user])
const toggleDrawer = () => {
setIsDrawerOpen(!isDrawerOpen)
}
const changeLanguage = (language: string) => {
i18n.changeLanguage(language)
localStorage.setItem("language", language)
}
const handleJp = () => {
changeLanguage("jp")
setActiveLang([true, false])
}
const handleEn = () => {
changeLanguage("en")
setActiveLang([false, true])
}
function openMenu() {
setOpen(!isOpen)
}
return (
<div className={styles.navigation} style={style}>
<div className={styles.menuIcon} onClick={openMenu}>
{isOpen ? (
<Icon name="fal fa-xmark" size="2.4" />
) : (
<MdOutlineShortText color={"#fff"} size={"2.4rem"} />
)}
</div>
<div className={styles.logo}>
<NavLink to={"/"}>
<img className={styles.logologo} src={logo} width={110} height={34} />
</NavLink>
</div>
<div className={styles.navbar}>
<NavLink to="/project-list" className={styles.navLink}>
{translate("navbar.projects")}
</NavLink>
<NavLink to="/team-search" className={styles.navLink}>
{translate("navbar.engineer-search")}
</NavLink>
<HashLink smooth to="/#build-team" className={styles.navLink}>
{translate("navbar.build-team")}
</HashLink>
<HashLink smooth to="/#contact" className={styles.navLink}>
{translate("navbar.contact")}
</HashLink>
</div>
<nav className={`${styles.menu} ${isOpen ? styles.open : styles.close}`}>
<div className={styles.menuHeader}>
<Icon
className={styles.closeIcon}
onClick={openMenu}
name="fal fa-xmark"
size="2.4"
/>
<div className={styles.logo} onClick={() => navigate("/")}>
<img src={logo} width={110} height={34} />
</div>
</div>
{isOpen && (
<div className={styles.menuContent}>
<div className={styles.menuBlock}>
<span>{translate("navbar.menu")}</span>
<Button className={styles.btnLang} mode="outline-small">
<span
style={{ color: `${activeLang?.[0] ? "#B5B8BF" : ""}` }}
onClick={handleJp}
>
Jp
</span>
/
<span
style={{
color: `${activeLang?.[1] ? "#B5B8BF" : ""}`,
}}
onClick={handleEn}
>
En
</span>
</Button>
</div>
<NavLink to="/project-list" className={styles.navLink}>
{translate("navbar.projects")}
</NavLink>
<NavLink to="/team-search" className={styles.navLink}>
{translate("navbar.engineer-search")}
</NavLink>
<HashLink smooth to="/#build-team" className={styles.navLink}>
{translate("navbar.build-team")}
</HashLink>
<HashLink smooth to="/#contact" className={styles.navLink}>
{translate("navbar.contact")}
</HashLink>
</div>
)}
</nav>
<div className={styles.rightSideWrap}>
{currentUser ? (
<div className={styles.userLogoBlock}>
<NavLink to={""}>
<IoMailOutline size={25} color="#fff" />
</NavLink>
{isMobile ? (
<div>
<Icon
onClick={() => setIsDrawerOpen(!isDrawerOpen)}
className={styles.userCircle}
name="fa-solid fa-circle-user"
size="large"
/>
</div>
) : (
<PopupOpener
mode={"click"}
placement="bottom-end"
offset={[60, 5]}
content={() => {
return (
<Menu>
<MenuItem
iconClassName={styles.iconSettings}
icon="fa-solid fa-gear"
label="Settings"
link={
currentUser.role === UserKind.engineer
? `/profile-engineer/${currentUser.id}`
: "/profile-company"
}
/>
<MenuItem
iconClassName={styles.iconSettings}
icon="fa-solid fa-arrow-right-from-bracket"
label="Sign out"
onClick={() => {
logout()
navigate("/")
}}
/>
</Menu>
)
}}
closeOnInteract={true}
>
{accountProfile && accountProfile.profilePicture ? (
<img
className={styles.profileImg}
src={Config.imageUrl + accountProfile.profilePicture}
alt="profile_logo"
/>
) : (
<Icon
className={styles.userCircle}
name="fa-solid fa-circle-user"
size="large"
/>
)}
</PopupOpener>
)}
</div>
) : (
<span
className={styles.signInBtn}
onClick={() => {
modal.open({
component: <UserSignInComponent />,
width: "80rem",
closeOnEsc: true,
closeOnOutsideClick: true,
modalClassName: styles.modal,
})
}}
>
{translate("registration.sign-in")}
</span>
)}
<Button className={styles.btnLang} mode="outline-small">
<span
style={{ color: `${activeLang?.[0] ? "#B5B8BF" : ""}` }}
onClick={handleJp}
>
Jp
</span>
/
<span
style={{
color: `${activeLang?.[1] ? "#B5B8BF" : ""}`,
}}
onClick={handleEn}
>
En
</span>
</Button>
</div>
{isDrawerOpen && (
<div
className={`${styles.drawerMenu} ${isDrawerOpen ? styles.open : styles.close}`}
>
<div className={styles.closeDrawer}>
<Icon
onClick={toggleDrawer}
name="fal fa-xmark"
size="2.4"
style={{ color: "#fff" }}
/>
</div>
{currentUser && (
<div className={styles.drawerHeader}>
<NavLink
to={
currentUser.role === UserKind.engineer
? `/profile-engineer/${currentUser.id}`
: "/profile-company"
}
>
<Icon
className={styles.userPicture}
name="fa-solid fa-circle-user"
size="auto"
/>
</NavLink>
<span className={styles.userName}>{currentUser.name}</span>
</div>
)}
<div className={styles.drawerContent}>
<NavLink to="" className={styles.drawerItemBlock}>
<Icon
name="fa-solid fa-gear"
size="2.2"
style={{ color: "#fff" }}
/>
<span className={styles.drawerItem}>Setting</span>
</NavLink>
<div
onClick={() => {
logout(), toggleDrawer(), navigate("/")
}}
className={styles.drawerItemBlock}
>
<Icon
name="fa-solid fa-arrow-right-from-bracket"
size="2.2"
style={{ color: "#fff" }}
/>
<span className={styles.drawerItem}>Sign out</span>
</div>
</div>
</div>
)}
</div>
)
}
Conclusion
By ensuring that the cookie attributes match when setting and removing cookies, you can help ensure the cookies are properly removed in both development and production environments. If you continue to experience issues, you might also want to check your browser console for any error messages or warnings that might provide additional context.