Da uma olhada na lib nookies
https://github.com/maticzav/nookies#readme
import { parseCookies, setCookie, destroyCookie } from 'nookies'
function handleClick() {
// Simply omit context parameter.
// Parse
const cookies = parseCookies()
console.log({ cookies })
// Set
setCookie(null, 'fromClient', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
// destroyCookie(null, 'cookieName')
}
export default function Me() {
return <button onClick={handleClick}>Set Cookie</button>
}
Exemplo de uso real
'use client'
import { parseCookies } from 'nookies'
import { ReactNode, useEffect } from 'react'
import { useRouter } from 'next/navigation'
export default function ProviderAuth({ children }: { children: ReactNode }) {
const { token } = parseCookies()
const router = useRouter()
useEffect(() => {
if (token !== process.env.NEXT_PUBLIC_SECRET_KEY) {
router.push('/')
}
}, [])
return <div>{children}</div>
}