5.1.0 • Published 5 months ago

cookies-next v5.1.0

Weekly downloads
810
License
MIT
Repository
github
Last release
5 months ago

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 cookies-next@4.3.0

Usage

Importing

For Next.js 15+:

// For client-side usage
import {
  getCookie,
  getCookies,
  setCookie,
  deleteCookie,
  hasCookie,
  useGetCookies,
  useSetCookie,
  useHasCookie,
  useDeleteCookie,
  useGetCookie,
} 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

Hooks

Using separate hook for each cookie function:

'use client';

import { useGetCookies, useSetCookie, useHasCookie, useDeleteCookie, useGetCookie } from 'cookies-next';

function ClientComponent() {
  const setCookie = useSetCookie();
  const hasCookie = useHasCookie();
  const deleteCookie = useDeleteCookie();
  const getCookies = useGetCookies();
  const getCookie = useGetCookie();

  setCookie('key', 'value');

  return (
    <div>
      <p>hasCookie - {JSON.stringify(hasCookie('key'))}</p>
      <p>getCookies - {JSON.stringify(getCookies)}</p>
      <p>getCookie - {getCookie('key')}</p>
      <button type="button" onClick={() => deleteCookie('key')}>
        deleteCookie
      </button>
    </div>
  );
}

Using one hook that returns all of the cookie functions:

'use client';

import { useCookiesNext } from 'cookies-next';

function ClientComponent() {
  const { setCookie, hasCookie, deleteCookie, getCookies, getCookie } = useCookiesNext();

  setCookie('key', 'value');

  return (
    <div>
      <p>hasCookie - {JSON.stringify(hasCookie('key'))}</p>
      <p>getCookies - {JSON.stringify(getCookies)}</p>
      <p>getCookie - {getCookie('key')}</p>
      <button type="button" onClick={() => deleteCookie('key')}>
        deleteCookie
      </button>
    </div>
  );
}

If you are going to perform actions on cookies inside a useEffect, make sure to add the cookie function returned from the hook to the dependency array.

const getCookies = useGetCookies();

useEffect(() => {
  console.log('getCookies', getCookies());
}, [getCookies]);

Client functions

'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');
  };

  /* .... */
}

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
  ❌ await setCookie("test", "value", { cookies }); // Won't work
  ❌ await 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 });

  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

next-firebase-auth-cookies@infinitebrahmanuniverse/nolb-coojovapos-pos@everything-registry/sub-chunk-1379nukleus-threenoot-cosmetics@stellaria/nova-test@gshah.dev/transparency-v0wph-proxy-nextwuthery-l10ntemplate-nextjs-tailwind-css@commonalityco/feature-graphiya-web-apexiya-web-apex-linkiya-web-apex-v2iya-web-apex-vinujrgcomponentskmd-uicds-support-chatbot@wechange/frontend-corekonnektive-sdk-nextjsstupendous-analyticsstupendous-analytics-nexttypesense-search-package-v1tosidestudio-account@apptoolkit/auth@agixt/interactive@cabin-id/nextjs@cabinid/client@cabinvn/cabinid-nextjs230105-woncheol-library-test-cookie@bracefinance/brace-sdk-demoyvr-coreupconta.frontend-utilszishop-login@finsel-dgi/pasby-next@ebanux/ebanux-utils@gumilang/3dlabtiten@gshah.dev/transparency@hanzo/brand@ibercore/next-auth@hitobit/client@gen3/frontend@everipedia/iq-login@luxfi/core@luxfi/ui@multiplatform.one/locales@netz-wire/cookie-consent@nickradford/next-shopify-auth@farbenmeer/deadbolt@mediblock/ui-kit@marketplace-ui/commerce-config@marketplace-ui/components@miza-react/miza-react-components@mbaluev/t1v3-shop-ssr-components@mbaluev/t1v3-shop-ssr-core@kenthackenough/staff@kenthackenough/ui@kenthackenough/web@protoxyz/auth-nextjs@quirks/next@realtoken/realt-commons@real-token/commons@open-condo/miniapp-utils@pocketcdp/pocket-for-nextjs@phemarketplace/shared@nuskin/foundation-core-app@rezamoosavi/asiastartup-npm-package@rezamoosavi/asiastartup-npm-package-kitmtxuilib-oldmtxuilibv2ms-ui-libraryoism-authpaydece-app-widgetpaydece-testsertropipayreact-banner-gdprnext-app-router-decoratornextpartynext-helpernext-interceptornew-package-v3peyvandrequest-next-pakokrmp-scriptsimple-nextjs-darkmodesiteecom-react-componentsidebut-xr-packagesiltioinfo-chat-gptinfo-chat-gpt-pckginfo-chat-gpt1hitobit-moduleslibsql-studio-guilive-hub-player-testsmann-componentsksdk-078-aklkkk-sdk-sskrosai-widget@workattackdev/wdk
5.1.0

5 months ago

5.0.2

7 months ago

5.0.1

7 months ago

5.0.0

8 months ago

4.3.0

9 months ago

4.2.1

1 year ago

4.2.0

1 year ago

4.1.1

1 year ago

3.0.0

2 years ago

4.1.0

2 years ago

4.0.0

2 years ago

2.1.2

2 years ago

2.1.1

3 years ago

2.0.5

3 years ago

2.1.0

3 years ago

2.0.4

3 years ago

2.0.3

4 years ago

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago