Cookie consent in NextJs

Matheswaaran
2 min readNov 1, 2022

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

For yarn:

yarn add cookies-next

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", {});
};

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.

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

Output

Be Amazed!

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

Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com

--

--