nghiepdev / next-universal-cookie

🍪 Provides a way to read, set and delete a cookie for Next.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

next-universal-cookie

NPM version NPM monthly download

Provides way to read, set and delete a cookie for Next.js similar to express such as req.cookies, res.cookie and res.clearCookie

Installation

npm install next-universal-cookie

Usage

With getServerSideProps and getInitialProps

import {GetServerSideProps, NextPageContext} from 'next';
import {applyServerSideCookie} from 'next-universal-cookie';

export const getServerSideProps: GetServerSideProps = async ({req, res}) => {
  applyServerSideCookie(req, res);

  // Typescript-ready

  // Parse all cookies
  const allCookies = req.cookies;

  // Set a cookie
  res.cookie();

  // Delete a cookie
  res.clearCookie();

  return {
    props: {},
  };
};

API Routes

// pages/api/index.ts
import {NextApiRequest, NextApiResponse} from 'next';
import {applyApiCookie} from 'next-universal-cookie';

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<{ok: boolean}>
) {
  applyApiCookie(req, res);

  // Typescript-ready
  const allCookies = req.cookies;
  res.cookie();
  res.clearCookie();

  res.json({ok: true});
}

API

import {applyServerSideCookie, applyApiCookie} from 'next-universal-cookie';

License

MIT

About

🍪 Provides a way to read, set and delete a cookie for Next.js

License:MIT License


Languages

Language:TypeScript 100.0%