By Alexander Yanovets

2009-02-10 07:49:51 8 Comments

How can I detect on the server (server-side) whether cookies in the browser are disabled? Is it possible?

Detailed explanation: I am processing an HTTP request on the server. I want to set a cookie via the Set-Cookie header. I need to know at that time whether the cookie will be set by the client browser or my request to set the cookie will be ignored.


@decoder7283 2018-07-19 00:49:35

NodeJS - Server Side - Cookie Check Redirect Middleware - Express Session/Cookie Parser


var express = require('express'),
    cookieParser = require('cookie-parser'),
    expressSession = require('express-session')


return (req, res, next) => {
  if(req.query.cookie && req.cookies.cookies_enabled)
    return res.redirect('' + req.path)
  if(typeof(req.cookies.cookies_enabled) === 'undefined' && typeof(req.query.cookie) === 'undefined') {
    return res.cookie('cookies_enabled', true, {
      path: '/',
      domain: '',
      maxAge: 900000, 
      httpOnly: true,
      secure: process.env.NODE_ENV ? true : false
    }).redirect(req.url + '?cookie=1')
  if(typeof(req.cookies.cookies_enabled) === 'undefined') {
    var target_page = '' + (req.url ? req.url : '')
    res.send('You must enable cookies to view this site.<br/>Once enabled, click <a href="' + target_page + '">here</a>.')

@balexandre 2009-02-10 08:11:27

You can use Javascript to accomplish that


function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    return null;

function eraseCookie(name) {
    createCookie(name, "", -1);

function areCookiesEnabled() {
    var r = false;
    createCookie("testing", "Hello", 1);
    if (readCookie("testing") != null) {
        r = true;
    return r;

Code to run:



This only works if Javascript is enabled!

@Adam 2010-05-18 16:17:15

The question is about how to detect cookies on the server side. Your code runs on the client side.

@balexandre 2010-05-18 18:41:41

Server Side - But he didn't specified what server language he is using! But the trick is the same... write a cookie and see if it's there... if it is, Cookies Enabled, if not... Disabled ;)

@Martijn 2011-05-04 09:19:11

It doesn't matter what language he is using on the server. This question can be answered in terms of HTTP requests/responses.

@Marquis of Lorne 2012-04-29 23:41:51

That Javascript code has to run in the browser to detect whether the browser has cookies enabled. It cannot run server-side.

@Chris 2012-09-30 22:46:14

The JavaScript Date.toGMTString() method is deprecated. You should use .toUTCString() instead.

@Chris 2012-09-30 23:04:06

@Adam - although the OP asked about server side, if you are trying to inform the user that the site requires cookies to be enabled to work fully, a client-side cookie test can achieve this (assuming JavaScript is enabled).

@Sandro L 2014-08-20 13:31:36

navigator.cookieEnabled (client-side JavaScript) works fine in all common browsers. Why don't use that?

@Clint Pachl 2014-09-10 21:25:24

Plus, this client-side code won't work on cookies that were set with the HttpOnly flag.

@Shoban 2009-02-10 07:56:36

I dont think there are direct ways to check. The best way is to store a value in the cookie and try to read them and decide whether cookies are enabled or not.

@thomasrutter 2009-02-26 12:28:36

A common way of checking for cookie support is via a redirect.

It's a good idea to only do this when the user is trying to do something that initiates a session, such as logging in, or adding something to their cart. Otherwise, depending on how you handle it, you're potentially blocking access to your entire site for users - or bots - that don't support cookies.

First, the server checks the login data as normal - if the login data is wrong the user receives that feedback as normal. If it's right, then the server immediately responds with a cookie and a redirect to a page which is designed to check for that cookie - which may just be the same URL but with some flag added to the query string. If that second page doesn't receive the cookie, then the user receives a message stating that they cannot log in because cookies are disabled on their browser.

If you're following the Post-Redirect-Get pattern for your login form already, then this setting and checking of the cookie does not add any additional requests - the cookie can be set during the existing redirect, and checked by the destination that loads after the redirect.

Now for why I only do a cookie test after a user-initiated action other than on every page load. I have seen sites implement a cookie test on every single page, not realising that this is going to have effects on things like search engines trying to crawl the site. That is, if a user has cookies enabled, then the test cookie is set once, so they only have to endure a redirect on the first page they request and from then on there are no redirects. However, for any browser or other user-agent, like a search engine, that doesn't return cookies, every single page could simply result in a redirect.

Another method of checking for cookie support is with Javascript - this way, no redirect is necessarily needed - you can write a cookie and read it back virtually immediately to see if it was stored and then retrieved. The downside to this is it runs in script on the client side - ie if you still want the message about whether cookies are supported to get back to the server, then you still have to organise that - such as with an Ajax call.

For my own application, I implement some protection for 'Login CSRF' attacks, a variant of CSRF attacks, by setting a cookie containing a random token on the login screen before the user logs in, and checking that token when the user submits their login details. Read more about Login CSRF from Google. A side effect of this is that the moment they do log in, I can check for the existence of that cookie - an extra redirect is not necessary.

@Zameer Khan 2014-06-06 12:10:07

The cookieEnabled property returns a Boolean value that specifies whether or not cookies are enabled in the browser

if (navigator.cookieEnabled) {
    // Cookies are enabled
else {
    // Cookies are disabled

@ZiggyTheHamster 2016-11-07 19:28:10

OP wanted to know how to detect it server-side.

@Steve 2019-10-23 14:25:12

Obviously, you'll have to get that info back to the server in a manner suitable for your application. It should be clear that it's impossible to determine whether a browser has cookies enabled without interacting with the browser.

@user3211045 2014-01-19 18:19:38

<?php   session_start();
  echo "Please enable cookie";

@user2511210 2013-11-13 08:36:57

check this code , it' will help you .


function visitor_is_enable_cookie() {
    $cn = 'cookie_is_enabled';
    if (isset($_COOKIE[$cn]))
        return true;
    elseif (isset($_SESSION[$cn]) && $_SESSION[$cn] === false)
        return false;

    // saving cookie ... and after it we have to redirect to get this
    setcookie($cn, '1');
    // redirect to get the cookie
        header("location: ".$_SERVER['REQUEST_URI'].'?nocookie') ;

    // cookie isn't availble
    $_SESSION[$cn] = false;
    return false;


@MayorMonty 2013-02-10 22:41:07

Use navigator.CookieEnabled for cookies enabled(it will return true of false) and the Html tag noscript. By the way navigator.cookieEnabled is javascript so don't type it in as HTML

@Evan M 2013-12-30 22:16:32

The question is regarding server-side checks, not client-side.

@Broote 2012-10-02 21:32:18

I'm using a much more simplified version of "balexandre"'s answer above. It tries to set, and read a session cookie for the sole purpose of determining if cookies are enabled. And yes, this requires that JavaScript is enabled as well. So you may want a tag in there if you care to have one.

// Cookie detection
document.cookie = "testing=cookies_enabled; path=/";
if(document.cookie.indexOf("testing=cookies_enabled") < 0)
    // however you want to handle if cookies are disabled
    alert("Cookies disabled");
    <!-- However you like handling your no JavaScript message -->
    <h1>This site requires JavaScript.</h1>

@thomasrutter 2012-10-02 04:18:30

Usually, you might only need to check for cookie support after the user has taken some action on the site, such as submitting a login form, adding an item to their cart, and so on.

For me currently, checking for cookie support goes hand-in-hand with CSRF (Cross-Site Request Forgery) prevention.

You should probably go elsewhere to read more about CSRF, but the idea behind it is that other sites may trick or your users into submitting a hidden form of their choosing to your own site. The way around this is to set a cookie when the viewer sees a form, and set a matching token as a hidden form element, and then when processing the form, check that both the cookie and hidden form element were set and match each other. If it is an attempted CSRF attack, the site won't be able to provide the hidden field to match the user's cookie, because the user's cookie won't be readable to them under the same-origin policy.

If a form is submitted having no cookie, but it does contain a valid-looking token, then you can conclude from this that the user has cookies disabled and throw up a message indicating that the user should enable cookies and re-try. The other possibility, of course, is that the user is the victim of an attempted CSRF attack. So blocking the user when the cookie doesn't match will also have the side-effect of preventing that attack.

@user1018130 2011-11-08 08:43:18

I always used this:


According to w3schools "The cookieEnabled property is supported in all major browsers.".

However, this works for me when i am using forms, where i can instruct the browser to send the additional information.

@Milan Gardian 2012-05-27 15:28:43

+1 from me. Any reason for the downvotes? This seems like a reasonable way to detect cookie blocking in JavaScript (and works in both Chrome and IE for me).

@TJ VanToll 2012-06-12 19:34:27

I believe the down votes are because the question specifically asked about how to detect support from the server side. This is the best way to test support on the client side.

@BryanH 2013-01-08 16:43:57

W3Schools is apparently not a credible source for HTML/Javascript/CSS/etc. information.

@StuckOnSimpleThings 2013-12-02 19:07:27

This only tests if the browser supports it. It does not test if it is enabled. Practically every browser supports it, so this seems to be pretty much worthless. Sorry.

@magritte 2011-10-03 15:01:41

If you only want to check if session cookies (cookies that exist for the lifetime of the session) are enabled, set your session mode to AutoDetect in your web.config file, then the Asp.Net framework will write a cookie to the client browser called AspxAutoDetectCookieSupport. You can then look for this cookie in the Request.Cookies collection to check if session cookies are enabled on the client.

E.g. in your web.config file set:

<sessionState cookieless="AutoDetect" />

Then check if cookies are enabled on the client with:

if (Request.Cookies["AspxAutoDetectCookieSupport"] != null)  { ... }

Sidenote: By default this is set to UseDeviceProfile, which will attempt to write cookies to the client so long as the client supports them, even if cookies are disabled. I find it slightly odd that this is the default option as it seems sort of pointless - sessions won't work with cookies disabled in the client browser with it set to UseDeviceProfile, and if you support cookieless mode for clients that don't support cookies, then why not use AutoDetect and support cookieless mode for clients that have them disabled...

@David Moorhouse 2012-11-09 02:40:31

Assumes ASP.NET The original question was technology neutral

@Lawrence Dol 2009-02-10 07:54:09

Send a redirect response with the cookie set; when processing the (special) redirected URL test for the cookie - if it's there redirect to normal processing, otherwise redirect to an error state.

Note that this can only tell you the browser permitted the cookie to be set, but not for how long. My FF allows me to force all cookies to "session" mode, unless the site is specifically added to an exception list - such cookies will be discarded when FF shuts down regardless of the server specified expiry. And this is the mode I run FF in always.

@Simon_Weaver 2009-05-23 05:57:43

except for stackoverflow?

@Lawrence Dol 2009-05-23 06:29:32

Except for a number of sites, one of which is indeed SO.

@MSalters 2009-02-10 08:39:57

The question whether cookies are "enabled" is too boolean. My browser (Opera) has a per-site cookie setting. Furthermore, that setting is not yes/no. The most useful form is in fact "session-only", ignoring the servers' expiry date. If you test it directly after setting, it will be there. Tomorrow, it won't.

Also, since it's a setting you can change, even testing whether cookies do remain only tells you about the setting when you tested. I might have decided to accept that one cookie, manually. If I keep being spammed, I can (and at times, will) just turn off cookies for that site.

@Alexander Yanovets 2009-02-10 11:06:45

Good point, but I just need to know if my Set-Cookie header will result in that next request from the same client will came with that cookie or not. It is not important for me if it is permanent or just session-only.

@Joonas Pulakka 2009-02-10 07:53:46

Try to store something into a cookie, and then read it. If you don't get what you expect, then cookies are probably disabled.

@Tom Lianza 2009-02-10 07:57:08

A lot of websites do this. It's not possible (on the server) to figure out if cookies are enabled on the first request, but you can implement a short redirect step to figure it out.

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] HTTP test server accepting GET/POST requests

  • 2011-04-20 04:17:11
  • John Twigg
  • 371431 View
  • 453 Score
  • 15 Answer
  • Tags:   http post

14 Answered Questions

[SOLVED] How do I set/unset a cookie with jQuery?

7 Answered Questions

[SOLVED] Do sessions really violate RESTfulness?

4 Answered Questions

[SOLVED] Why is it common to put CSRF prevention tokens in cookies?

11 Answered Questions

9 Answered Questions

[SOLVED] How do browser cookie domains work?

6 Answered Questions

[SOLVED] What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

22 Answered Questions

[SOLVED] Cookie blocked/not saved in IFRAME in Internet Explorer

8 Answered Questions

[SOLVED] Are HTTP cookies port specific?

2 Answered Questions

Sponsored Content