website-logomedCode

Next.js 14: Implementing an Effective Cookie Consent Banner

Discover how Next.js 14 enhances your website with an Effective cookie Consent banner, and discover the best UI designer cookies component...
Viva Code| February 26, 2024
next.js
Next.js 14: Implementing an Effective Cookie Consent Banner
Share

#Next.js #Cookie #Banner #SEO #Tools

The Complete Next.js 14 Cookie Consent Banner Design Guide:

Understanding the Importance of Cookie Consent Banners:

Cookie consent banners serve as a notification to visitors that a website uses cookies to track user data. By displaying a cookie banner, websites can ensure transparency and obtain user consent before collecting any personal information. This builds trust with users and demonstrates compliance with data protection laws.

How to Implement a Cookie Banner on Next.js 14:

1.First, once Node is installed, create a Next.js app. Run the command below, select No for TypeScript, Yes for use app router, and the defaults for every other option.

npx create-next-app@latest cookie-banner

2.install (gtag.js) package node

npm i ga-gtag

3.create a util folder and create file Helper.jsx

export function getLocalStorage(key, defaultValue) {
  const stickyValue = localStorage.getItem(key);


  return stickyValue !== null && stickyValue !== "undefined"
    ? JSON.parse(stickyValue)
    : defaultValue;
}


export function setLocalStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

4.create a CookieBanner.jsx file inside component folder

"use client";
import Link from "next/link";
import { getLocalStorage, setLocalStorage } from "../utils/Helper";
import { useEffect, useState } from "react";
export default function CookieBanner() {
  const [cookieConsent, setCookieConsent] = useState(false);
  useEffect(() => {
    const storedCookieConsent = getLocalStorage("cookie_consent", null);
    setCookieConsent(storedCookieConsent);
  }, [setCookieConsent]);
  useEffect(() => {
    const newValue = cookieConsent ? "granted" : "denied";


    window.gtag("consent", "update", {
      analytics_storage: newValue,
    });


    setLocalStorage("cookie_consent", cookieConsent);
    console.log("Cookie Consent: ", cookieConsent);
  }, [cookieConsent]);
  return (
    <div
      className={`${
        cookieConsent === true
          ? "hidden"
          : "flex  flex-col fixed inset-x-0 bottom-0 z-20  justify-between gap-x-8 gap-y-4 bg-white p-6 ring-1 ring-gray-900/10 md:flex-row md:items-center lg:px-8 xs:block"
      }`}
    >
      <p className="max-w-4xl text-sm leading-6 text-gray-900">
        This website uses cookies to enhance your browsing experience, analyze
        site traffic, and serve better user experiences. By continuing to use
        this site, you consent to our use of cookies. Learn more in our{" "}
        <Link className="font-semibold text-[#8A2BE2]" href="/cookies">
          cookie policy
        </Link>
      </p>


      <div className="flex gap-2">
        <div className="mr-16 flex flex-none items-center gap-x-5">
          <button
            onClick={() => setCookieConsent(true)}
            type="button"
            className="rounded-md bg-gray-900 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900"
          >
            Accept all 🍪
          </button>
          <button
            onClick={() => setCookieConsent(false)}
            type="button"
            className="text-sm font-semibold leading-6 text-gray-900"
          >
            Reject all
          </button>
        </div>
      </div>
    </div>
  );
}

note:inside this code you have a ui designe for cookie banner

5.go to layout.js file and add cookieBanner.jsx as this:

import { Inter } from "next/font/google";
import "./globals.css";
import dynamic from "next/dynamic";
const NavBar = dynamic(() => import("./components/NavBar"));
const Footer = dynamic(() => import("./components/Footer"));
import AuthProvider from "./components/authProvider/AuthProvider";
import CookieBanner from "./components/Cookies";
export const inter = Inter({
  subsets: ["latin"],
  display: "swap",
});
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className} suppressHydrationWarning={true}>
        <AuthProvider>
          <NavBar />
          {children}
          <CookieBanner />
          <Footer />
        </AuthProvider>
      </body>
    </html>
  );
}

Conclusion:

In conclusion, implementing a cookie consent banner on your Next.js 14 website is essential for ensuring user privacy and compliance with regulations. By following best practices for design and implementation, you can enhance the user experience and build trust with your audience. Remember to regularly update your cookie banner to reflect any changes in regulations or your website's data processing practices.

For more information on cookie banners and web design, visit our blog for updates and tips on UI design and user experience

more article for Next.js 🦙



This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy