next-universal-cookie
v3.1.0
Published
🍪 Provides way to read, set and delete a cookie for Next.js
Downloads
2,756
Readme
next-universal-cookie
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
res.cookie();
// Delete
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();
// Response
res.json({
ok: true,
});
}
API
import {applyServerSideCookie, applyApiCookie} from 'next-universal-cookie';
License
MIT