Cookie consent in NextJs

Afzal Imdad - Jun 10 - - Dev Community

Image description

This article discusses how to add cookie consent to a NextJs app using cookies-next package.

Install the required packages:

To install the package, type one of the following commands based on your package manager

For npm:

npm install cookies-next
Enter fullscreen mode Exit fullscreen mode

For yarn:

yarn add cookies-next
Enter fullscreen mode Exit fullscreen mode

Cookie consent implementation:

When there is no cookie present, the cookie consent popup should be shown.

cookies-next package has hasCookie, setCookie functions with which the cookies can be accessed and managed. Here is how its managed in a React component.

const [showConsent, setShowConsent] = React.useState(true);
React.useEffect(() => {
  setShowConsent(hasCookie("localConsent"));
}, []);
const acceptCookie = () => {
  setShowConsent(true);
  setCookie("localConsent", "true", {});
};
Enter fullscreen mode Exit fullscreen mode

Here is a full example of how a cookie consent component works in Next.js. Add the component to your pages/index.js to be visible.

import React from "react";
import { hasCookie, setCookie } from "cookies-next";

const CookieConsent = (props) => {
  const [showConsent, setShowConsent] = React.useState(true);

  React.useEffect(() => {
    setShowConsent(hasCookie("localConsent"));
  }, []);

  const acceptCookie = () => {
    setShowConsent(true);
    setCookie("localConsent", "true", {});
  };

  if (showConsent) {
    return null;
  }

  return (
    <div className="fixed inset-0 bg-slate-700 bg-opacity-70">
      <div className="fixed bottom-0 left-0 right-0 flex items-center justify-between px-4 py-8 bg-gray-100">
        <span className="text-dark text-base mr-16">
          This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy.
        </span>
        <button className="bg-green-500 py-2 px-8 rounded text-white" onClick={() => acceptCookie()}>
          Accept
        </button>
      </div>
    </div>
  );
};

export default CookieConsent;
Enter fullscreen mode Exit fullscreen mode

Note: The above example uses tailwindcss. To know more, refer here

Output

Be Amazed!

Hooray! We have successfully added cookie consent in Next.js.

. . . . . . . . . . . . . . . . . .
Terabox Video Player