Reusables

Cookies

Tools to handle cookies in client and server environments.

Client

Simple methods to manage cookies on the client components.

npx shadcn@latest add "https://reusables.vercel.app/r/cookies-client"

Usage

const handleSetCookie = () => {
  // Set a cookie
  ClientCookies.set("user-preference", "dark-mode")
}
 
const handleGetCookie = () => {
  // Get the value of cookie named 'user-preference'
  const preference = ClientCookies.get("user-preference")
  console.log("Cookie value:", preference)
}
 
const handleDeleteCookie = () => {
  // Delete the cookie named 'user-preference'
  ClientCookies.delete("user-preference")
}

Server

Functions to manage cookies in Next.js server and server components.

If you’re using Next.js 15, use ServerCookiesNext15 as it requires async/await.

npx shadcn@latest add "https://reusables.vercel.app/r/cookies-server"

Usage

Next.js 15

export default async function CookiesServerNext15Example() {
  //Set a cookie
  await ServerCookiesNext15.set("language", "en")
 
  // Get a cookie
  const language = await ServerCookiesNext15.get("language")
  console.log("Current language:", language)
 
  // Delete a cookie
  await ServerCookiesNext15.delete("language")
 
  return (
    <div className="space-y-4">
      <div>
        <h3>Next.js 15+ Cookie Values:</h3>
      </div>
    </div>
  )
}

THis will only work in Next.js 13-14. You will need to uncomment ServerCookies to use it.

export default async function CookiesServerExample() {
  // Set a cookie
  ServerCookies.set("theme", "dark")
 
  // Get a cookie
  const theme = ServerCookies.get("theme")
 
  // Delete a cookie
  ServerCookies.delete("theme")
 
  return (
    <div className="space-y-4">
      <div>
        <h3>Legacy Server Cookie Values:</h3>
      </div>
    </div>
  )
}

Features

  • Type-safe cookie operations
  • Secure by default (HTTPS only)
  • Configurable options (path, domain, sameSite)
  • Server-side rendering compatible
Edit on GitHub

Last updated on

On this page