Skip to main content

WEBINARNavigating Consent Mode V2: How Should I Prepare?

|

30 April, 2024

3 pm CET (8 am CT)

Register now

How to handle the server side cookies when using CookieYes?

Last updated on March 25, 2024

To handle the server side cookies on your website, first identify which categories of cookies are allowed to be set. This can be done by verifying the user’s consent state using standard cookie handling.

The sample code to handle the server side cookie while using CookieYes in some programming languages are listed below:

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

app.get('/', (req, res) => {
 const cookieValue = req.cookies['cookieyes-consent'];

 if (cookieValue) {
   const cookiePairs = cookieValue.split(',').map((pair) => pair.trim());
   const cookieObj = {};

   cookiePairs.forEach((pair) => {
     const [key, value] = pair.split(':');
     cookieObj[key] = value;
   });
   console.log(cookieObj);
  
 if (
     [
       'functional',
       'analytics',
       'performance',
       'advertisement',
       'other',
     ].every(
       (key) => cookieObj[key] === 'no' || !cookieObj.hasOwnProperty(key)
     )
   ) {
     console.log(
       'The user has opted out of cookies, set strictly necessary cookies only'
     );
   } else {
     if (cookieObj['functional'] === 'yes') {
       console.log('The user has accepted functional cookies');
     } else {
       console.log('The user has NOT accepted functional cookies');
     }


     if (cookieObj['analytics'] === 'yes') {
       console.log('The user has accepted analytics cookies');
     } else {
       console.log('The user has NOT accepted analytics cookies');
     }

     if (cookieObj['performance'] === 'yes') {
       console.log('The user has accepted performance cookies');
     } else {
       console.log('The user has NOT accepted performance cookies');
     }

     if (cookieObj['advertisement'] === 'yes') {
       console.log('The user has accepted advertisement cookies');
     } else {
       console.log('The user has NOT accepted advertisement cookies');
     }


     if ('other' in cookieObj) {
       if (cookieObj['other'] === 'yes') {
         console.log('The user has accepted other cookies');
       } else {
         console.log('The user has NOT accepted other cookies');
       }
     }
   }
 }
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening to port ${port}`));
import http.server
import os
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer

class MyRequestHandler(BaseHTTPRequestHandler):
   def do_GET(self):
       # Parse cookies from the request
       cookie = SimpleCookie(self.headers.get('Cookie'))

       # Get the value of cookieyes-consent
       if 'cookieyes-consent' in cookie:
           print(cookie['cookieyes-consent'].value)
           cookieConsent = {k: v for k, v in [p.split(":") for p in cookie['cookieyes-consent'].value.split(",")]}

           #Checking cookie preferences
           # user rejects all cookies,allow necesssary cookies only
           if (cookieConsent.get('functional')!='yes' and cookieConsent.get('analytics')!='yes' and cookieConsent.get('performance')!='yes' and cookieConsent.get('advertisement')!='yes' and cookieConsent.get('other')!='yes') :
               print("The user has opted out of cookies, set strictly necessary cookies only")
           
               # user consents to preferred cookies,
           else:
               #checks whether accepts functional cookies
               if cookieConsent.get('functional')=='yes':
                   print("User accepts functional cookies")
               else:
                   print("User do not accept functional cookies ")
               
               #checks whether accepts analytics cookies
               if cookieConsent.get('analytics')=='yes':
                   print("User accepts analytics cookies")
               else:
                   print("User do not accept analytics cookies ")
               
               #checks whether accepts performance cookies
               if cookieConsent.get('performance')=='yes':
                   print("User accepts perfomance cookies")
               else:
                   print("User do not accept performance cookies ")
              
               #checks whether accepts advertisement cookies
               if cookieConsent.get('advertisement')=='yes':
                   print("User accepts advertisement cookies")
               else:
                   print("User do not accept advertisement cookies ")
              
               #checks whether accepts other cookies
               if cookieConsent.get('other')=='yes':
                   print("User accepts other cookies")
               else:
                   print("User do not accept other cookies ")
      
       # Cookieyes cookies are not set
       else:
           print("The user has opted out of cookies, set strictly necessary cookies only")


port = int(os.environ.get('PORT', 8000))
httpd = HTTPServer(('localhost', port), MyRequestHandler)
httpd.serve_forever()
<?php

function cookiereader()
{
//if cookieyes cookies are set
   if (isset($_COOKIE['cookieyes-consent'])) {
       // Read current user consent
       $CookieConsent = array_column(array_map(function ($pair) {
           return explode(':', $pair);
       }, explode(',', $_COOKIE['cookieyes-consent'])), 1, 0);



       //if the user has rejected all cookies     
       if (!filter_var($CookieConsent['functional'], FILTER_VALIDATE_BOOLEAN) && !filter_var($CookieConsent['analytics'], FILTER_VALIDATE_BOOLEAN) && !filter_var($CookieConsent['performance'], FILTER_VALIDATE_BOOLEAN) && !filter_var($CookieConsent['advertisement'], FILTER_VALIDATE_BOOLEAN) && !filter_var($CookieConsent['other'], FILTER_VALIDATE_BOOLEAN)) {
           echo "The user has opted out of cookies, set strictly necessary cookies only.";
       }

       //Checking for user preferences
       else {
           //checking whether functional cookies are accepted
           if (filter_var($CookieConsent['functional'], FILTER_VALIDATE_BOOLEAN)) {
               echo "The user has accepted functional cookies.";
           } else {
               echo "The user has NOT accepted functional cookies.";
           }

           //checking whether analytics cookies are accepted
           if (filter_var($CookieConsent['analytics'], FILTER_VALIDATE_BOOLEAN)) {
               echo "The user has accepted analytics cookies.";
           } else {
               echo "The user has NOT accepted analytics cookies.";
           }

           //checking whether performance cookies are accepted
           if (filter_var($CookieConsent['performance'], FILTER_VALIDATE_BOOLEAN)) {
               echo "The user has accepted performance cookies.";
           } else {
               echo "The user has NOT accepted performance cookies.";
           }

           //checking whether advertisement cookies are accepted
           if (filter_var($CookieConsent['advertisement'], FILTER_VALIDATE_BOOLEAN)) {
               echo "The user has accepted advertisement cookies.";
           } else {
               echo "The user has NOT accepted advertisement cookies.";
           }

           //checking whether other cookies are accepted
           if (filter_var($CookieConsent['other'], FILTER_VALIDATE_BOOLEAN)) {
               echo "The user has accepted other category cookies.";
           } else {
               echo "The user has NOT accepted other category cookies.";
           }
       }
   } else {
       echo "The user has not accepted cookies - set strictly necessary cookies only";

   }

}
cookiereader();
package main

import (
   "fmt"
   "net/http"
   "strings"
)

func main() {
   http.HandleFunc("/", func(w http.ResponseWriter, r * http.Request) {

       cookie, err: = r.Cookie("cookieyes-consent")
       if err != nil {
           if err == http.ErrNoCookie {
               http.Error(w, "Cookie not set", http.StatusNotFound)
           } else {
               http.Error(w, err.Error(), http.StatusInternalServerError)
           }
           return
       }

       cookieConsent: = make(map[string] string)
       for _, pair: = range strings.Split(cookie.Value, ",") {
           keyValue: = strings.Split(pair, ":")
           if len(keyValue) == 2 {
               cookieConsent[keyValue[0]] = keyValue[1]
           }
       }


       // if cookies are rejected,set necesarry cookies only
       if cookieConsent["advertisement"] == "no" && cookieConsent["functional"] == "no" && cookieConsent["performance"] == "no" && cookieConsent["analytics"] == "no" && cookieConsent["other"] == "no" {
           fmt.Println("The user has opted out of cookies, set strictly necessary cookies only")
               // checking cookie preferences set by user
       } else {
         

                        // if functional cookies are accepted
           if cookieConsent["functional"] == "yes" {
                   fmt.Println("The user has accepted functional cookies")
                       // if functional cookies are reejcted
               } else {
                   fmt.Println("The user has NOT accepted functional cookies")
               }
              

                        // if analytics cookies are accepted
           if cookieConsent["analytics"] == "yes" {
                   fmt.Println("The user has accepted analytics cookies")
                       // if analytics cookies are rejected
               } else {
                   fmt.Println("The user has NOT accepted analytics cookies")
               }
                  

                        // if perfomance cookies are accepted
           if cookieConsent["performance"] == "yes" {
                   fmt.Println("The user has accepted performance cookies")
                       // if perfomance cookies are rejected
               } else {
                   fmt.Println("The user has NOT accepted performance cookies")
               }
                

                        // if advertisement cookies are accepted
           if cookieConsent["advertisement"] == "yes" {
                   fmt.Println("The user has accepted advertisement cookies")
                       // if advertisement cookies are rejected
               } else {
                   fmt.Println("The user has NOT accepted advertisement cookies")
               }
              

                     // if other cookies are accepted
           if cookieConsent["other"] == "yes" {
               fmt.Println("The user has accepted other cookies")
                   // if other cookies are rejected
           } else {
               fmt.Println("The user has NOT accepted other cookies")
           }


       }

   })

  
 //Start the server on port 8080
   http.ListenAndServe(":8000", nil)
}

Have more questions?

Reach out to us and we'll answer them.

Contact us