• Stars
    star
    2,269
  • Rank 20,309 (Top 0.5 %)
  • Language
    TypeScript
  • Created almost 7 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸͺ A set of cookie helpers for Next.js

nookies πŸͺ

Working npm version

A collection of cookie helpers for Next.js

Features

  • ✨ SSR support, for setter, parser and destroy
  • βš™οΈ Custom Express server support
  • πŸͺΆ super light
  • πŸ›‘ perfect for authentication

Setting and destroying cookies also works on server-side.

Quick start

yarn add nookies

You can play with the example code here.

ServerSide cookies

import nookies from 'nookies'

export default function Me() {
  return <div>My profile</div>
}

export async function getServerSideProps(ctx) {
  // Parse
  const cookies = nookies.get(ctx)

  // Set
  nookies.set(ctx, 'fromGetInitialProps', 'value', {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
  })

  // Destroy
  // nookies.destroy(ctx, 'cookieName')

  return { cookies }
}

Client-only Cookies

import { parseCookies, setCookie, destroyCookie } from 'nookies'

function handleClick() {
  // Simply omit context parameter.
  // Parse
  const cookies = parseCookies()
  console.log({ cookies })

  // Set
  setCookie(null, 'fromClient', 'value', {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
  })

  // Destroy
  // destroyCookie(null, 'cookieName')
}

export default function Me() {
  return <button onClick={handleClick}>Set Cookie</button>
}

Custom Express server cookies

const express = require('express');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const { parseCookies, setCookie, destroyCookie } = require('nookies');

app.prepare()
    .then(() => {
        const server = express();

        server.get('/page', (req, res) => {

          // Notice how the request object is passed
          const parsedCookies = parseCookies({ req });

          // Notice how the response object is passed
          setCookie({ res }, 'fromServer', 'value', {
            maxAge: 30 * 24 * 60 * 60,
            path: '/page',
          });

          // destroyCookie({ res }, 'fromServer');

          return handle(req, res);
        });

    );

Reference

For client side usage, omit the ctx parameter. You can do so by setting it to an empty object ({}), null or undefined.

parseCookies(ctx, options) or nookies.get(ctx, options)

  • ctx: Next.js context || (Express request object)
  • options:
    • decode: a custom resolver function (default: decodeURIComponent)

setCookie(ctx, name, value, options) or nookies.set(ctx, name, value, options)

Don't forget to end your response on the server with res.send().

  • ctx: (Next.js context) || (Express request object)
  • name: cookie name
  • value: cookie value
  • options:
    • domain
    • encode
    • expires
    • httpOnly
    • maxAge
    • path
    • sameSite
    • secure

destroyCookie(ctx, name, options) or nookies.destroy(ctx, 'token', options)

Don't forget to end your response on the server with res.send(). This might be the reason your cookie isn't removed.

  • ctx: (Next.js context) || (Express response object)
  • name: cookie name
  • options:
    • domain
    • path

License

MIT

More Repositories

1

graphql-shield

πŸ›‘ A GraphQL tool to ease the creation of permission layer.
TypeScript
3,555
star
2

emma-cli

πŸ“¦ Terminal assistant to find and install node packages.
TypeScript
1,228
star
3

graphql-middleware

Split up your GraphQL resolvers in middleware functions
TypeScript
1,134
star
4

swift-graphql

A GraphQL client that lets you forget about GraphQL.
Swift
598
star
5

ink-table

πŸ“A table component for Ink.
TypeScript
180
star
6

graphql-middleware-apollo-upload-server

Upload is hard, that's why we do it for you. πŸŽ‰
TypeScript
130
star
7

ink-autocomplete

🧠 An autocomplete component for Ink.
JavaScript
80
star
8

label-sync

🏷 A delightful companion to manage Github Labels across multiple repositories.
TypeScript
60
star
9

creato

πŸ‘¨πŸ»β€πŸ­ create-app for any occasion
TypeScript
24
star
10

graphql-middleware-forward-binding

GraphQL Binding forwardTo plugin for GraphQL Middleware
TypeScript
23
star
11

graphql-server-file-upload-example

πŸ’Ύ GraphQL Server examples: File API
TypeScript
21
star
12

graphql-server-github-auth-example

GraphQL Server examples: Authentication
TypeScript
20
star
13

kayu

TypeScript GraphQL client that lets you forget about GraphQL
TypeScript
15
star
14

sponsorsme

A lightweight utility to check whether a user sponsors you.
TypeScript
14
star
15

prisma-converter

Convert your Prisma 1.0 datamodel to Prisma 2.0
TypeScript
13
star
16

resk

βœ‚οΈ Automatically create gists from your code.
JavaScript
9
star
17

multilinestring

The missing template literal for NodeJS.
TypeScript
7
star
18

gimb-events

🎟A ticketing system for all Gimnazija Bežigrad events
TypeScript
4
star
19

sessions

Manage NodeJS server sessions easily in-memory or in Redis.
TypeScript
4
star
20

reserve-npm

πŸ“¦ A CLI tool which helps you reserve a NPM package name
TypeScript
3
star
21

github-tree

πŸ™ Github API commits made easy peasy
TypeScript
3
star
22

semantha

πŸ’β€β™€οΈ A delightful mono-repository assistant.
TypeScript
2
star
23

multiwatch

A web application for better multiple stopwatch-times handling.
JavaScript
1
star
24

graphql-vs-rest

Elm
1
star
25

resizable-dots

Simple Elm app.
HTML
1
star
26

nepremicnine

Repozitorij s projektno nalogo pri Programiranju 1
HTML
1
star
27

stars

Draw.
Elm
1
star