Next.js Discord

Discord Forum

Dynamic Script Load/Unload

Answered
Dutch posted this in #help-forum
Open in Discord
Avatar
DutchOP
So i have a custom analytics <script> tag, and i want to load it if the user accepts Analytics Cookies, and unload if he later disables it.
I created a custom component that returns the script tag based on the cookie value, and imported it on the layout.tsx file, how may i unload and load the script?
Also i have a hook to save updated cookie values and i was wondering if i could use the hook to reload the page or alike.
Answered by B33fb0n3
you can do a check if the user accepted the cookies. For that check if there is a cookie like CookiesAccepted and if not, show the banner (and don't show the script component) and when the user accepts the cookies, set the cookie & reload the page. That can be done for example using router.refresh()
View full answer

19 Replies

Avatar
you can do a check if the user accepted the cookies. For that check if there is a cookie like CookiesAccepted and if not, show the banner (and don't show the script component) and when the user accepts the cookies, set the cookie & reload the page. That can be done for example using router.refresh()
Answer
Avatar
DutchOP
i tried using router.refresh() in my cookies hook and it didn’t refresh the page
i will show you my code when i get home tho, about 1 hour from now
Avatar
when will you send it?
Avatar
DutchOP
oh shit i forgot
im arriving at school, ill send in a bit
Avatar
DutchOP
'use client'

import { useIsClient } from '@/helpers/hooks/useIsClient'
import { useState, useEffect } from 'react'
import { useMemo } from 'react'

export function useCookies() {
  const isClient = useIsClient()
  const cookies_ = isClient ? window?.document?.cookie : ''

  return useMemo(() => {
    return cookies_.split(';').reduce((acc, cookie) => {
      const [key, value] = cookie.split('=')
      acc.set(key.trim(), value)
      return acc
    }, new Map<string, string>())
  }, [cookies_])
}

export interface CookiePreferences {
  necessary: boolean
  analytics: boolean
}

export const useCookiePreferences = () => {
  const cookies = useCookies()
  const [cookiePreferences, setCookiePreferences] = useState<CookiePreferences>(
    {
      necessary: true,
      analytics: false
    }
  )
  const [showBanner, setShowBanner] = useState(true)

  useEffect(() => {
    const savedPreferences = cookies.get('cookiePreferences')
    if (savedPreferences) {
      setCookiePreferences(JSON.parse(savedPreferences))
      setShowBanner(false)
    }
  }, [cookies])

  const savePreferences = (preferences: typeof cookiePreferences) => {
    setCookiePreferences(preferences)
    const expires = new Date(Date.now() + 365 * 864e5).toUTCString()
    document.cookie = `cookiePreferences=${JSON.stringify(preferences)}; expires=${expires}; path=/`

    window.location.reload()
  }

  return {
    cookiePreferences,
    setCookiePreferences,
    showBanner,
    setShowBanner,
    savePreferences
  }
}
@B33fb0n3 this is my hook, and i want to reload/refresh the page when i run savePreferences()
Avatar
do yourself a favor and check all the stuff serverside. Use the cookies() function to access the cookies server and use the .get() function to retrieve a specific value that you want to check.

Also when setting the cookie instead of doing that somehow clientside, do it serverside via a server action or route handler. Like that the router.refresh() should work fine
Avatar
DutchOP
wait theres a cookies function within nextjs?
💀
Avatar
of course. Nextjs is a full stack environment. See here: https://nextjs.org/docs/app/api-reference/functions/cookies
Avatar
DutchOP
but that gives me an issue since i need the clientside thingy for the banner to show
i waas able to do it with router.refresh, thanks
Avatar
so is your inital issue already resolved like that?
Avatar
DutchOP
yes
i had to use it outside the hook tho
i used it on my cookies context
Avatar
happy to help