Next.js Discord

Discord Forum

Need advices on cookies (for consent)

Unanswered
Savannah posted this in #help-forum
Open in Discord
SavannahOP
Hey guys, i've just made a system that allow users to accept or reject cookies from the website, but i'd like to have your opinions on how i've done things, and whether or not you see any areas for improvement

Wouldn't it be better to use an external lib like this one (cookies-next) ? https://matheswaaran.medium.com/cookie-consent-in-nextjs-a05af7c941c8

4 Replies

SavannahOP
my code :
Home.tsx :
"use client";
import "@/styles/website/pages/Home.scss";
import {Award, Earth, Hotel, User} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import {useEffect, useState} from "react";
import CookiesConsent from "@/app/componens/website/Banners/CookiesConsent";

export default function Home() {
    const [showCookiesConsentBanner, setShowCookiesConsentBanner] = useState(true);

    const sendEmail = () => {
        fetch('/api/emails/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({})
        })
            .then(response => response.json())
            .then(data => console.log('data mail', data))
            .catch(error => console.error('error mail', error));
    };

    useEffect(() => {
        fetch('/api/users/consent/cookies/has')
            .then(response => response.json())
            .then(data => setShowCookiesConsentBanner(!data.has))
            .catch(error => console.error('error fetching cookies consent', error));
    }, []);

    const handleCookiesAccepted = () => {
        setShowCookiesConsentBanner(false);
    };

    return (
        <main className="wrapper-home">
            {showCookiesConsentBanner && <CookiesConsent onAccept={handleCookiesAccepted} />}
        </main>
    );
}
The route to check if cookies exist or not :
import {NextResponse} from "next/server";
import {cookies} from "next/headers";

export async function GET(req: any, res: any){
    return NextResponse.json({has: cookies().has('consent')})
}
`
The route to set cookies :
import {NextResponse} from "next/server";
import {cookies} from "next/headers";
import {encrypt} from "@/app/lib/cookies/protection";

export async function POST(req: any, res: any) {
    const {consent} = await req.json()
    cookies().set('consent', consent)
    return NextResponse.json({message: 'Cookies consent set'})
}
`