Cookies in JavaScript, React, and Next.js
🍪

Cookies in JavaScript, React, and Next.js

Read Time in min.
5
Live
Live
Tags
programming
Created
Mar 6, 2022
Layers of abstraction are great for building things quickly without having to cobble together all of your own bricks. Sometimes, when you need to build something atypical, you require a more complete understanding, and the “magic” going on behind the scenes needs to be understood. That’s where I’m at with cookies in front-end web development. The goal of this post is to demystify cookies, first in Javascript, then more specifically in React and Next.js.

What are Cookies?

Cookies are name-value pairs, stored in small text files, on your computer. They were created to allow websites to “remember” information about a user who has returned to the page after navigating away.
 

Cookies vs Local Storage vs Session Storage

  • Cookies are older, Local Storage and Session Storage are newer
  • Local Storage persists between sessions, Session Storage does not
  • All three are easily read or changed in browser, so should not be used for sensitive data
  • Cookies can be set to HTTP only, which prevents JavaScript from accessing them
  • Cookies are sent on every request, so should be kept small
  • Local and Session Storage have a much higher capacity
 

When to Use Cookies?

Authentication seems to be an excellent use case for cookies. The data required is small, and it’s very convenient to ignore the overhead of sending a token stored in Local or Session storage each time.
 

Cookes in JavaScript

// document.cookie is "magic" // Write Cookie document.cookie = "username=Drew Bidlen"; // Add an expiration date (browser close by default) document.cookie = "username=Drew Bidlen; expires=Thu, 10 Mar 2021 12:00:00 UTC"; // Read Cookie let x = document.cookie;
 

Cookies in React

react-cookie” seems to be the go-to package to manage cookies in React. The following snippets from their documentation make it clear how to manage, read, and write cookies.
// Root.jsx import React from 'react'; import App from './App'; import { CookiesProvider } from 'react-cookie'; export default function Root() { return ( <CookiesProvider> <App /> </CookiesProvider> ); } // App.jsx import React from 'react'; import { useCookies } from 'react-cookie'; import NameForm from './NameForm'; function App() { const [cookies, setCookie] = useCookies(['name']); function onChange(newName) { setCookie('name', newName, { path: '/' }); } return ( <div> <NameForm name={cookies.name} onChange={onChange} /> {cookies.name && <h1>Hello {cookies.name}!</h1>} </div> ); } export default App;
 

Cookies in Next.js

cookies-next” seems to be the go-to package to manage cookies in React. The following snippets from their documentation make it clear how to manage, read, and write cookies on the client, a Next API endpoint, or a page using SSR.
 

Client

import { getCookies, setCookies, removeCookies } from 'cookies-next'; // we can use it anywhere getCookies(); getCookie('key'); setCookies('key', 'value'); removeCookies('key');
 

API

// /page/api/example.js import type { NextApiRequest, NextApiResponse } from 'next' import { getCookies, getCookie, setCookies, removeCookies } from 'cookies-next' export default async function handler(req, res) { setCookies('server-key', 'value', { req, res, maxAge: 60 * 60 * 24 }); getCookie('key', { req, res }); getCookies({ req, res }); removeCookies('key', { req, res }); return res.status(200).json({ message: "ok" }) }
 

SSR

// /page/index.js import React from 'react' import { getCookies, getCookie, setCookies, removeCookies } from 'cookies-next'; const Home = () => { return ( <div>page content</div> ) } export const getServerSideProps = ({ req, res }) => { setCookies('test', 'value', { req, res, maxAge: 60 * 6 * 24 }); getCookie('test', { req, res}); getCookies({ req, res}); removeCookies('test', { req, res}); return { props: {}}; } export default Home
 
“Cookie” no longer looks like a word to me so I think we’re done here! Hope this has been helpful!