npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cookies-next

v5.0.2

Published

Set, Get, Remove cookies on both client and server side with Next.js

Downloads

2,052,845

Readme

cookies-next

npm version GitHub code size in bytes

A versatile cookie management library for Next.js applications, supporting both client-side and server-side operations.

Features

  • Works on client-side, server-side rendering, and API routes
  • Supports Next.js 13+ App Router and Server Components
  • TypeScript compatible
  • Lightweight and easy to use

Installation

For Next.js versions 15 and above, use the latest version of cookies-next:

npm install --save cookies-next@latest

For Next.js versions 12.2.0 to 14.x, use cookies-next version 4.3.0:

npm install --save [email protected]

Usage

Importing

For Next.js 15+:

// For client-side usage
import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next/client';

// For server-side usage
import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next/server';

Also, you can leave the decision of which import to use to the the library itself, by importing from the root:

import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';

For Next.js 12.2.0 to 13.x:

import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';

Basic Operations

Set a cookie

setCookie('key', 'value', options);

Get a cookie

const value = getCookie('key', options);

Get all cookies

const cookies = getCookies(options);

Check if a cookie exists

const exists = hasCookie('key', options);

Delete a cookie

deleteCookie('key', options);

Client-side Usage

'use client';

import { getCookies, setCookie, deleteCookie, getCookie } from 'cookies-next/client';

function ClientComponent() {
  /* 
 ❗❗❗ In a client component, it's highly recommended to use cookies-next functions within useEffect or in event handlers; otherwise, you might encounter hydration mismatch errors. - 
 https://react.dev/link/hydration-mismatch.   
 */

  useEffect(() => {
    getCookies();
    getCookie('key');
    setCookie('key', 'value');
    deleteCookie('key');
    hasCookie('key');
  }, []);

  const handleClick = () => {
    getCookies();
    getCookie('key');
    setCookie('key', 'value');
    deleteCookie('key');
    hasCookie('key');
  };

  /* .... */
}
// Use anywhere in client-side code

Server-side Usage (App Router)

In Server Components:

import { getCookie, getCookies, hasCookie } from 'cookies-next/server';
import { cookies } from 'next/headers';

export const ServerComponent = async () => {
  // Read-only operations in Server Components
  const value = await getCookie('test', { cookies });
  const allCookies = await getCookies({ cookies });
  const exists = await hasCookie('test', { cookies });

  // Note: It's not possible to update cookies in Server Components
  ❌ setCookie("test", "value", { cookies }); // Won't work
  ❌ deleteCookie('test', { cookies }); // Won't work

  return <div>...</div>;
};

In Server Actions:

'use server';

import { cookies } from 'next/headers';
import { setCookie, deleteCookie, getCookie, getCookies, hasCookie } from 'cookies-next/server';

export async function serverAction() {
  await setCookie('test', 'value', { cookies });
  await deleteCookie('test', { cookies });
  await getCookie('test', { cookies });
  await getCookies({ cookies });
  await hasCookie('test', { cookies });
}

API Routes (App Router)

import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { deleteCookie, getCookie, setCookie, hasCookie, getCookies } from 'cookies-next/server';

export async function GET(req: NextRequest) {
  const res = new NextResponse();
  await setCookie('test', 'value', { res, req });
  await getCookie('test', { res, req });
  await getCookies({ res, req });
  await deleteCookie('test', { res, req });
  await hasCookie('test', { req, res });

  // Using cookies function
  await setCookie('test1', 'value', { cookies });
  await getCookie('test1', { cookies });
  await getCookies({ cookies });
  await deleteCookie('test1', { cookies });
  await hasCookie('test1', { cookies });

  return res;
}

Middleware

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getCookie, setCookie, deleteCookie, hasCookie, getCookies } from 'cookies-next/server';

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  await setCookie('test', 'value', { res, req });
  await hasCookie('test', { req, res });
  await deleteCookie('test', { res, req });
  await getCookie('test', { res, req });
  await getCookies({ res, req });

  // Note: cookies function from next/headers cannot be used in middleware
  ❌ setCookie('test', 'value', { cookies }); // Won't work

  return res;
}

API

setCookie(key, value, options)

Sets a cookie.

setCookie('key', 'value', options);

getCookie(key, options)

Retrieves a specific cookie.

const value = getCookie('key', options);

getCookies(options)

Retrieves all cookies.

const cookies = getCookies(options);

hasCookie(key, options)

Checks if a cookie exists.

const exists = hasCookie('key', options);

deleteCookie(key, options)

Deletes a cookie.

deleteCookie('key', options);

Options

  • req: Required for server-side operations (except when using cookies function)
  • res: Required for server-side operations (except when using cookies function)
  • cookies: Function from next/headers, used in App Router for server-side operations
  • domain: Specifies the cookie's domain
  • path: Specifies the cookie's path
  • maxAge: Specifies the cookie's maximum age in seconds
  • httpOnly: Sets the HttpOnly flag
  • secure: Sets the Secure flag
  • sameSite: Sets the SameSite attribute ('strict', 'lax', or 'none')

For more detailed options, refer to the cookie specification.

License

MIT