Managing Cookies and Ensuring User Privacy Compliance.

Configuring cookies within your application using "next-cookies"

In your online browsing experience, you've likely encountered those pesky pop-ups that ask for your consent to accept cookies. These cookies aren't edible treats; rather, they are small data fragments stored by servers in your web browser and sent with every request. They play a significant role in providing a user with a smooth experience, from basic processes like saving a user's theme preference or cart content to more complex processes like authorization on protected pages.

While cookies play a pivotal role in enhancing the user experience, mishandling them—such as collecting and storing cookies without proper consent—can result in violations of a user's privacy rights.

This article will guide you through implementing a cookie consent component using the npm package next-cookie.


To follow this tutorial, it is essential that you understand what cookies are and have a basic understanding of web development. Additionally, familiarity with the difference between authorization and authentication would be advantageous.

What are Cookies?

Cookies are small data fragments stored by servers in your web browser and sent with every request. They play a significant role in providing you with a smooth user experience. A cookie could contain unique identifiers, such as your login credentials or your preferred visual theme—be it the soothing light mode or the sleek dark mode.

Cookies can also be used maliciously to track sensitive information like passwords, addresses, and payment card numbers. This is why it is essential for a developer to store them securely. The common types of cookies used on the web are usually Authentication Cookies and Tracking Cookies.

Authentication Cookies

These are typically used by web servers to identify the logged-in user and the associated account. These cookies are sent with every request that requires authorization. Without them, users would need to authenticate themselves on every request. The security of an authentication cookie depends on the security of the issuing website and the user's web browser.

Tracking Cookies

These are used to track a user's long-term browsing history, these cookies have raised privacy concerns, leading to the development of legal frameworks for user privacy. Tracking cookies serve purposes like analytics, personalization, and targeted advertising, emphasizing the importance of obtaining a user's consent.

Cookie consent refers to the practice of obtaining user consent before placing or storing cookies on visitors’ devices through a website or online service. It is an essential aspect of data privacy regulations, with specific conditions that must be met for consent to be considered valid:

While consent for storing essential cookies like authorization cookies is usually not required, obtaining consent before storing non-essential tracking cookies is crucial.
  • Granular Consent: Users should have the option to provide separate consents for different types of cookies (e.g., essential, analytics, marketing). This ensures granular control over personal data.

  • Freely given: Consent must be given voluntarily and users should have a genuine choice to accept or reject the use of cookies. That means they should not be forced into giving consent with terms or conditions.

  • Prior Information: Users must receive prior information about the use of cookies, including the types of cookies used, their purpose, and the duration of storage

  • Unambiguous: Consent must be expressed through affirmative action or clear affirmative statement. It should not be inferred from inactivity or pre-ticked boxes. Users need to actively indicate their agreement or disagreement with the use of cookies.

  • Revocable: Users should have the right to withdraw their consent at any time. The process for revoking consent should be as easy as granting it. Users should be informed about how they can withdraw their consent and have their cookies preferences updated or deleted.

  • Demonstratable: Websites should maintain records of obtained consents to demonstrate compliance with data protection regulations. It is important to keep track of when and how consent was obtained, including any accompanying information provided to users.

By adhering to these valid conditions for cookie consent, companies can ensure that they respect users’ privacy rights, maintain transparency, and meet the requirements of data protection regulations.

Over the years, various legal frameworks have been developed but the most popular still remains the General Data Protection Regulation (GDPR). Under the GDPR, user consent for non-essential (tracking) cookies is a mandatory requirement. Websites must obtain clear and informed consent from visitors before storing or retrieving cookies on their devices. The website must also provide information on the cookies being stored, the type of information that is collected, and for what purpose this data is collected.

Each legal framework governs a region of users, the GDPR for example governs the European Union

Some other Legal Frameworks are:

  1. ePrivacy Directive:

    • Oversees electronic communications within the European Union.
  2. California Consumer Privacy Act (CCPA):

    • Regulates the protection of California residents' personal information.
  3. Cookie Law (UK)

    • Governs the use of cookies in the United Kingdom, emphasizing user consent.
  4. Personal Information Protection and Electronic Documents Act (PIPEDA):

    • A Canadian law governing the private sector's collection and use of personal information.
  5. Nigeria Data Protection Regulation (NDPR):

    • Mandates consent as the lawful basis for installing cookies, outlining guidelines for cookie deployment in Nigeria. For more details, refer to Read more

Failing to comply with cookie regulations can result in substantial fines for website owners.

As stated earlier, we will be implementing this cookie consent using the npm package next-cookie in a Nextjs application and Tailwindcss for styling . The npm package next-cookie that allows you to easily set cookies for client-side rendered components.

This serves as a basic boilerplate for implementing a cookies consent component and further research should be done before adding to your codebase.

Step 1:

Install next-cookie

npm i next-cookie

Step 2 :

Create a blank Nextjs project and create a CookiesConsent component

import React, {useState} from 'react'
import Link from 'next/link';

const CookiesConsent = () => {
  // this component will show fixed to the bottom screen of your device
  return (
    <div className='fixed bottom-0 left-0 w-full p-4 bg-black/50 text-white'>
        <p className='text-md font-satoshiMedium text-center'>This site uses cookies to offer you a better browsing experience. For further information on how we use cookies you can read our <Link href="/policy"   target='blank' className='underline text-sm'>Cookies & Privacy Policie</Link> </p>
        <div className='mt-1 flex justify-center'>    <button className='bg-primaryPurple rounded-md text-sm text-white px-4 py-2 hover:scale-105 hover:text-gray-200' onClick={acceptCookies}>Accept Cookies</button></div>


export default CookiesConsent;

Step 3:

Import the necessary modules

import React, { useState } from 'react';
import { useCookie } from 'next-cookie'; // Importing the useCookie hook from next-cookie
import Link from 'next/link';

Step 4:

Use useCookie Hook and Initialize accepted State

const cookie = useCookie();
const consent: boolean = cookie.get("cookie-consent");
const [accepted, setAccepted] = useState<boolean>(consent);

Step 5:

Set expiration date, Define acceptCookies and declineCookies function

// Expiration date set to one month
const oneMonth = 30 * 24 * 60 * 60 * 1000;
const expirationDate = new Date( + oneMonth);

// Accept cookies function
const acceptCookies = () => {
    "cookie-consent", true, {
    httpOnly: false,
    secure: true,
    sameSite: "strict",
    expires: expirationDate,
    path: "/",
const declineCookies = () => {
    "cookie-consent", false, {
    httpOnly: false,
    secure: true,
    sameSite: "strict",
    expires: expirationDate,
    path: "/",

Step 6:

Conditionally render the Jsx component based on the value of accept:

if (accepted !== undefined) {
  return null; // The banner is hidden once the accpted is no longer undefined
return (
  <div className='fixed bottom-0 left-0 w-full p-4 bg-black/50 text-white'>
    <p className='text-md font-satoshiMedium text-center'>
      This site uses cookies to offer you a better browsing experience. For further information on how we use cookies you can read our{' '}
      <Link href="/policy" target='blank' className='underline text-sm'>Cookies & Privacy Policy</Link>
    <div className='mt-1 flex justify-center gap-4'>
      <button className='bg-primaryPurple rounded-md text-sm text-white px-4 py-2 hover:scale-105 hover:text-gray-200' onClick={acceptCookies}>
        Accept Cookies
          <button className='bg-red-500 rounded-md text-sm text-white px-4 py-2 hover:scale-105 hover:text-gray-200' onClick={declineCookies}>
          Decline Cookies

The finalized codebase can be accessed on this GitHub Gist.

Best Practice

When configuring cookies, it is essential to adhere to specific security measures, including:

  1. httpOnly: false - The httpOnly property is set to false, this allows the client side access and modify the cookie value.

  2. secure: true - The secure property is set to true, indicating that the cookie should only be transmitted over secure, encrypted connections (HTTPS). This enhances the security and privacy of the cookie data

  3. sameSite: "strict" - The sameSite property is set to "strict", this setting ensures that the cookie is only sent in first-party contexts, which helps protect against cross-site request forgery (CSRF) attacks.

  4. expires: expirationDate - The expires property is set to a variable expirationDate, which specifies when the cookie should expire.

  5. path: "/" - The path property specifies the path on the website for which the cookie is valid. In this case, it's set to /, indicating that the cookie is valid for the entire website.


It is essentially that a user be informed on the cookies being stored on their device as serving both as a measure to uphold user privacy and to protect them from potential cyber exploits. In my research, I discovered two websites that facilitate checking the cookies employed by a website.:

  1. CookieServe - is a free online tool that scans your website for cookies. Enter the URL and it will start scanning it, providing a detailed result in seconds

  2. CookieYes scanner - is a free tool that scans the website URL for cookies. It works just like CookieServe.


  1. Functions: cookies | Next.js (

  2. Cookies (

  3. Everything You Need to Know About Cookies for Web Development (

  4. How to Block Cookie Consent Pop-Ups in Your Browser (

  5. What is GDPR, the EU’s new data protection law? -