<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ cookies - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ cookies - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:30:57 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/cookies/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Cookies to Customize a Web Page's Content ]]>
                </title>
                <description>
                    <![CDATA[ If you develop websites or web apps, someday you’ll have to deal with cookies. That’s why I decided to write this tutorial on how to use cookies to customize a web page according to the previous web page the user comes from.  I wrote this tutorial us... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-cookies-to-customize-web-page-content/</link>
                <guid isPermaLink="false">66bdff670b4523e3b8b99097</guid>
                
                    <category>
                        <![CDATA[ cookies ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Marco Venturi ]]>
                </dc:creator>
                <pubDate>Tue, 30 May 2023 22:04:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/vyshnavi-bisani-z8kriatLFdA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you develop websites or web apps, someday you’ll have to deal with cookies. That’s why I decided to write this tutorial on how to use cookies to customize a web page according to the previous web page the user comes from. </p>
<p>I wrote this tutorial using PHP, but you can set cookies also by using other popular programming languages such as Java, Python, and others.</p>
<p>Before going deep with the details, let's go through a brief introduction and some recommendations.</p>
<h2 id="heading-what-are-cookies">What are Cookies?</h2>
<p>Cookies play a vital role in how websites function. They can also enhance a user's browsing experience. </p>
<p>In simple terms, a cookie is a small file that websites store on a user's computer or device while they navigate through various web pages. These files contain data that are utilized by websites to remember certain information and settings, ultimately improving the performance and customization of the website for the user.</p>
<p>When a user visits a website, the site's server sends a cookie to the user's browser, which then stores it on their computer or device. The next time the user visits the same website, the browser sends the stored cookie back to the server. This enables the website to recognize the user, remember their preferences, and provide personalized content.</p>
<p>Cookies serve various functions, such as remembering login information, language preferences, and shopping cart contents. </p>
<p>For example, when you visit an online shopping website and add items to your cart, cookies help in retaining those items even if you navigate to other pages. Cookies can also remember your login details, so you don't have to re-enter them every time you visit a website.</p>
<p>Cookies can also be used for tracking user behavior and gathering information about website usage. This information is often anonymous and helps website owners analyze traffic patterns, identify popular pages, and improve their website's design and functionality. </p>
<p>Advertisers also use cookies to deliver targeted advertisements based on users' browsing habits and interests. This enables them to show relevant ads that are more likely to be of interest to the user.</p>
<h3 id="heading-a-note-about-cookies-and-user-privacy">A Note about Cookies and User Privacy</h3>
<p>Cookies are designed to be a tool for enhancing user experience and improving website functionality. But concerns about privacy and security have led to the development of regulations and guidelines for using cookies. Many websites now provide cookie consent notices, allowing users to choose whether they want to accept or reject cookies.</p>
<p>Over the past few decades, the use of cookies has been subject to extensive discussion by regulatory bodies, emphasizing the significance of ensuring users are fully informed about their implementation. </p>
<p>Progress has been made in this direction, including the introduction of the General Data Protection Regulation (GDPR) by the European Union (EU). For more comprehensive information, you can get detailed insights from the official web portal of the EU. </p>
<p>If you are considering the integration of cookies into your application, I highly recommend discussing the implications with the legal department of your company or consulting with legal professionals who possess expertise in this domain. By doing so, you can ensure compliance with the legal and regulatory frameworks governing the use of cookies, safeguarding user privacy in the process.</p>
<h2 id="heading-lets-get-started">Let’s Get Started</h2>
<p>Let’s assume I’m running a pet lovers e-commerce site, and I’m implementing a content marketing strategy to attract new customers. </p>
<p>I create one informational page for cats lovers and another one for dogs lovers. Both pages point to the same page where I give further details about having pets. </p>
<p>I want this page to show specific (targeted) ads according to the page the user comes from: if they visited the page about cats, I want them to see ads about cat food. If they visited the one about dogs, I want them to see ads about dog food.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-124.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-lets-code">Let’s Code</h2>
<p>I’m building three pages:</p>
<ol>
<li>Cat's lovers page: mainPageCat.php (screenshot below)</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-125.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ol start="2">
<li>Dog's lover page: mainPageDog.php</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-126.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ol start="3">
<li>The target page: cookieTest.php</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-127.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>While building pages 1 and 2, I set cookies using the PHP <code>setcookie()</code> function. For the page about cats, I pass the function these parameters:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$cookie_name = <span class="hljs-string">"cat"</span>;
$cookie_value = <span class="hljs-string">"catFoodAds"</span>;
setcookie($cookie_name, $cookie_value, time() + (<span class="hljs-number">86400</span> * <span class="hljs-number">30</span>), <span class="hljs-string">"/"</span>); <span class="hljs-comment">// 86400 = 1 day</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>For the page about dogs, I pass these parameters:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$cookie_name = <span class="hljs-string">"dog"</span>;
$cookie_value = <span class="hljs-string">"dogFoodAds"</span>;
setcookie($cookie_name, $cookie_value, time() + (<span class="hljs-number">86400</span> * <span class="hljs-number">30</span>), <span class="hljs-string">"/"</span>); <span class="hljs-comment">// 86400 = 1 day</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>For the “further information” page I add some logic. If the cat cookie is stored, I add a CSS class to the dog ads card to hide it. I do the same with the cat ads card if the cookie stored is the one from the dog page.</p>
<pre><code class="lang-php">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">row</span>"&gt;
            &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">col</span>-<span class="hljs-title">md</span>-3"&gt;
                &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span> &lt;?<span class="hljs-title">php</span> <span class="hljs-title">if</span>(<span class="hljs-title">isset</span>($<span class="hljs-title">_COOKIE</span>['<span class="hljs-title">dog</span>'])) <span class="hljs-title">echo</span> ' <span class="hljs-title">cookieClass</span>'; ?&gt;" <span class="hljs-title">style</span>="<span class="hljs-title">width</span>: 18<span class="hljs-title">rem</span>;"&gt;
                    &lt;<span class="hljs-title">img</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">img</span>-<span class="hljs-title">top</span>" <span class="hljs-title">src</span>="<span class="hljs-title">https</span>://<span class="hljs-title">images</span>.<span class="hljs-title">unsplash</span>.<span class="hljs-title">com</span>/<span class="hljs-title">photo</span>-1518791841217-8<span class="hljs-title">f162f1e1131</span>?<span class="hljs-title">ixlib</span>=<span class="hljs-title">rb</span>-1.2.1&amp;<span class="hljs-title">ixid</span>=<span class="hljs-title">MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDl8fHxlbnwwfHx8fA</span>%3<span class="hljs-title">D</span>%3<span class="hljs-title">D</span>&amp;<span class="hljs-title">w</span>=1000&amp;<span class="hljs-title">q</span>=80" <span class="hljs-title">alt</span>="<span class="hljs-title">Card</span> <span class="hljs-title">image</span> <span class="hljs-title">cap</span>"&gt;
                    &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">body</span>"&gt;
                        &lt;<span class="hljs-title">h5</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">title</span>"&gt;<span class="hljs-title">Buy</span> <span class="hljs-title">Food</span> <span class="hljs-title">for</span> <span class="hljs-title">Cats</span>&lt;/<span class="hljs-title">h5</span>&gt;
                        &lt;<span class="hljs-title">h6</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">subtitle</span> <span class="hljs-title">mb</span>-2 <span class="hljs-title">text</span>-<span class="hljs-title">muted</span>"&gt;<span class="hljs-title">Excellent</span> <span class="hljs-title">Food</span>&lt;/<span class="hljs-title">h6</span>&gt;
                        &lt;<span class="hljs-title">p</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">text</span>"&gt;<span class="hljs-title">Don</span>'<span class="hljs-title">t</span> <span class="hljs-title">know</span> <span class="hljs-title">what</span> <span class="hljs-title">else</span> <span class="hljs-title">I</span> <span class="hljs-title">could</span> <span class="hljs-title">say</span> <span class="hljs-title">about</span> <span class="hljs-title">cat</span> <span class="hljs-title">food</span>.&lt;/<span class="hljs-title">p</span>&gt;
                        &lt;<span class="hljs-title">a</span> <span class="hljs-title">href</span>="#" <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">link</span>"&gt;<span class="hljs-title">Buy</span>&lt;/<span class="hljs-title">a</span>&gt;
                    &lt;/<span class="hljs-title">div</span>&gt;
                &lt;/<span class="hljs-title">div</span>&gt;
            &lt;/<span class="hljs-title">div</span>&gt;
            &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">col</span>-<span class="hljs-title">md</span>-3"&gt;
                &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span> <span class="hljs-title">ml</span>-5 &lt;?<span class="hljs-title">php</span> <span class="hljs-title">if</span>(<span class="hljs-title">isset</span>($<span class="hljs-title">_COOKIE</span>['<span class="hljs-title">cat</span>'])) <span class="hljs-title">echo</span> ' <span class="hljs-title">cookieClass</span>'; ?&gt;" <span class="hljs-title">style</span>="<span class="hljs-title">width</span>: 18<span class="hljs-title">rem</span>;"&gt;
                    &lt;<span class="hljs-title">img</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">img</span>-<span class="hljs-title">top</span>" <span class="hljs-title">src</span>="<span class="hljs-title">https</span>://<span class="hljs-title">images</span>.<span class="hljs-title">unsplash</span>.<span class="hljs-title">com</span>/<span class="hljs-title">photo</span>-1561037404-61<span class="hljs-title">cd46aa615b</span>?<span class="hljs-title">ixlib</span>=<span class="hljs-title">rb</span>-1.2.1&amp;<span class="hljs-title">ixid</span>=<span class="hljs-title">MnwxMjA3fDB8MHxjb2xsZWN0aW9uLXBhZ2V8MXwxMTU1Mjc2N3x8ZW58MHx8fHw</span>%3<span class="hljs-title">D</span>&amp;<span class="hljs-title">w</span>=1000&amp;<span class="hljs-title">q</span>=80" <span class="hljs-title">alt</span>="<span class="hljs-title">Card</span> <span class="hljs-title">image</span> <span class="hljs-title">cap</span>"&gt;    
                    &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">body</span>"&gt;
                        &lt;<span class="hljs-title">h5</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">title</span>"&gt;<span class="hljs-title">Buy</span> <span class="hljs-title">Food</span> <span class="hljs-title">for</span> <span class="hljs-title">Dogs</span>&lt;/<span class="hljs-title">h5</span>&gt;
                        &lt;<span class="hljs-title">h6</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">subtitle</span> <span class="hljs-title">mb</span>-2 <span class="hljs-title">text</span>-<span class="hljs-title">muted</span>"&gt;<span class="hljs-title">Excellent</span> <span class="hljs-title">Food</span>&lt;/<span class="hljs-title">h6</span>&gt;
                        &lt;<span class="hljs-title">p</span> <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">text</span>"&gt;<span class="hljs-title">Don</span>'<span class="hljs-title">t</span> <span class="hljs-title">know</span> <span class="hljs-title">what</span> <span class="hljs-title">else</span> <span class="hljs-title">I</span> <span class="hljs-title">could</span> <span class="hljs-title">say</span> <span class="hljs-title">about</span> <span class="hljs-title">dog</span> <span class="hljs-title">food</span>.&lt;/<span class="hljs-title">p</span>&gt;
                        &lt;<span class="hljs-title">a</span> <span class="hljs-title">href</span>="#" <span class="hljs-title">class</span>="<span class="hljs-title">card</span>-<span class="hljs-title">link</span>"&gt;<span class="hljs-title">Buy</span>&lt;/<span class="hljs-title">a</span>&gt;
                    &lt;/<span class="hljs-title">div</span>&gt;
                &lt;/<span class="hljs-title">div</span>&gt;
            &lt;/<span class="hljs-title">div</span>&gt;
        &lt;/<span class="hljs-title">div</span>&gt;</span>
</code></pre>
<h2 id="heading-lets-see-how-it-works">Let’s see how it works</h2>
<p>I test the flow as a user who wants to visit the page about cats. I type in my browser URL bar:</p>
<p>https:///mainPageCat.php</p>
<p>As you can see, I see the page I built and the cookie is stored in my browser</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-128.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If I click the call to action (blue button), I see the further details page with cat food ads only:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-129.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let’s now test the flow for dog lovers. First I delete cookies from my browser (or use the incognito mode) and then I visit this URL:</p>
<p>https:///mainPageDog.php</p>
<p>This is what I see:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-130.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As we can see again, I see the page I built and the cookie is stored in my browser</p>
<p>If I click the call to action (blue button), I see the further details page with dog food ads only.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-131.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Done! This is a simple and quick example of how you can use cookies to customize the content of your web pages. You can find the Github repo <a target="_blank" href="https://github.com/mventuri/cookiesPhp">here</a> with the full code.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Everything You Need to Know About Cookies for Web Development ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered how you can sign in to a website once and remain signed in, even if you close your browser? Or added an item to your shopping cart without signing in at all? Whether you know it or not, cookies are everywhere, and for better or... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/everything-you-need-to-know-about-cookies-for-web-development/</link>
                <guid isPermaLink="false">66ac87f29c95a40246abe1b4</guid>
                
                    <category>
                        <![CDATA[ cookies ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kristofer Koishigawa ]]>
                </dc:creator>
                <pubDate>Wed, 03 Feb 2021 06:14:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/602cb40c0a2838549dcc6af3.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered how you can sign in to a website once and remain signed in, even if you close your browser? Or added an item to your shopping cart without signing in at all?</p>
<p>Whether you know it or not, cookies are everywhere, and for better or worse, they completely changed the way we use the web.</p>
<p>In this article, we'll go over the history of cookies, how they work, how to use them in JavaScript, and some security concerns to keep in mind.</p>
<h2 id="heading-a-brief-history-of-cookies">A brief history of cookies</h2>
<p>HTTP, or the Hypertext Transfer Protocol, is a stateless protocol. According to Wikipedia, its a stateless protocol because it "does not require the HTTP server to retain information or status about each user for the duration of multiple requests."</p>
<p>You can still see this today with simple websites – you type in the URL to the browser, the browser makes a request to a server somewhere, and the server returns the files to render the page and the connection is closed.</p>
<p>Now imagine that you need to sign in to a website to see certain content, like with LinkedIn. The process is largely the same as the one above, but you're presented with a form to enter in your email address and password.</p>
<p>You enter that information in and your browser sends it to the server. The server checks your login information, and if everything looks good, it sends the data needed to render the page back to your browser.</p>
<p>But if LinkedIn was truly stateless, once you navigate to a different page, the server would not remember that you just signed in. It would ask you to enter in your email address and password again, check them, then send over the data to render the new page.</p>
<p>That would be super frustrating, wouldn't it? A lot of developers thought so, too, and found different ways to create stateful sessions on the web.</p>
<h3 id="heading-the-invention-of-the-http-cookie">The invention of the HTTP cookie</h3>
<p>Lou Montoulli, a developer at Netscape in the early 90s, had a problem – he was developing an online store for another company, MCI, which would store the items in each customer's cart on its servers. This meant that people had to create an account first, it was slow, and it took up a lot of storage.</p>
<p>MCI requested for all of this data to be stored on each customer's own computer instead. Also, they wanted everything to work without customers having to sign in first.</p>
<p>To solve this, Lou turned to an idea that was already pretty well known among programmers: the magic cookie.</p>
<p>A magic cookie, or just cookie, is a bit of data that's passed between two computer programs. They're "magic" because the data in the cookie is often a random key or token, and is really just meant for the software using it.</p>
<p>Lou took the magic cookie concept and applied it to the online store, and later to browsers as a whole.</p>
<p>Now that you know about their history, let's take a quick look at how cookies are used to create stateful sessions on the web.</p>
<h2 id="heading-how-cookies-work">How cookies work</h2>
<p>One way to think of cookies is that they're a bit like the wristbands you get when you visit an amusement park.</p>
<p>For example, when you sign in to a website, it's like the process of entering an amusement park. First you pay for a ticket, then when you enter the park, the staff checks your ticket and gives you a wristband.</p>
<p>This is like how you sign in – the server checks your username and password, creates and stores a session, generates a unique session id, and sends back a cookie with the session id.</p>
<p>(Note that the session id is <em>not</em> your password, but is something completely separate and generated on the fly. Proper password handling and authentication is outside the scope of this article, but you can find some in depth guides <a target="_blank" href="https://www.freecodecamp.org/news/search/?query=authentication">here</a>.)</p>
<p>While you're in the amusement park, you can go on any ride by showing your wristband. </p>
<p>Similarly, when you make requests to the website you're signed in to, your browser sends your cookie with your session id back to the server. The server checks for your session using your session id, then returns data for your request.</p>
<p>Finally, once you leave the amusement park, your wristband no longer works – you can't use it to get back into the park or go on more rides. </p>
<p>This is like signing out of a website. Your browser sends your sign out request to the server with your cookie, the server removes your session, and lets your browser know to remove your session id cookie.</p>
<p>If you want to get back into the amusement park, you'd have to buy another ticket and get another wristband. In other words, if you want to continue using the website, you'd have to sign back in.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/fireship-cookies.png" alt="Image" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://www.youtube.com/watch?v=UBUNrFtufWo">Session vs Token Authentication in 100 Seconds</a> (YouTube)</em></p>
<p>This is just a simple example of how cookies can be used to keep you signed in to websites. They can be used to remember your setting for dark mode, to track your behavior on a website, and so much more.</p>
<h2 id="heading-how-to-use-cookies">How to use cookies</h2>
<p>Now that you know about the history of cookies and why they're used, let's look at some of the limitations of using cookies, then dive into some simple examples.</p>
<h3 id="heading-cookie-limitations">Cookie limitations</h3>
<p>Cookies are quite limited compared to some modern alternatives to storing data in the browser like <code>localStorage</code> or <code>sessionStorage</code>. Here's a rundown of cookies compared to those other technologies:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Cookies</td><td>Local Storage</td><td>Session Storage</td></tr>
</thead>
<tbody>
<tr>
<td>Capacity</td><td>4KB</td><td>10MB</td><td>5MB</td></tr>
<tr>
<td>Accessible from</td><td>Any window</td><td>Any window</td><td>Same tab</td></tr>
<tr>
<td>Expires</td><td>Manually set</td><td>Never</td><td>On tab close</td></tr>
<tr>
<td>Storage location</td><td>Browser and server</td><td>Browser only</td><td>Browser only</td></tr>
<tr>
<td>Sent with requests</td><td>Yes</td><td>No</td><td>No</td></tr>
</tbody>
</table>
</div><p>Based on: <a target="_blank" href="https://www.youtube.com/watch?v=AwicscsvGLg">cookies vs localStorage vs sessionStorage - Beau teaches JavaScript</a> (YouTube)</p>
<p>Cookies are a much older technology, and have a very limited capacity. Still, there's quite a bit you can do with them. And their small size makes it easy for the browser to send cookies with each request to the server.</p>
<p>It's also worth mentioning that browsers only allow cookies to work from one domain for security reasons.</p>
<p>So if you sign in to your bank at, say, ally.com, then cookies will only work within that domain and its subdomains. For example, your <code>ally.com</code> cookie will work on <code>ally.com</code>, <code>ally.com/about</code>, and the subdomain <code>www.ally.com</code>, but not <code>axos.com</code>.</p>
<p>This means that, even if you have accounts and are signed in at both <code>ally.com</code> and <code>axos.com</code>, those sites won't be able to read each other's cookies.</p>
<p>It's important to remember that your cookies are sent with every request you make in the browser. This is very convenient, but has some serious security implications we'll get into later.</p>
<p>Finally, if there's one thing you take away from this article, just remember that cookies are meant to be openly read and sent, so you should never store sensitive information like passwords in them.</p>
<h3 id="heading-how-to-set-a-cookie-in-javascript">How to set a cookie in JavaScript</h3>
<p>Cookies are really just strings with key / value pairs. Though you'll probably work with cookies more on the backend, there may be times you'll want to set a cookie on the client side.</p>
<p>Here's how to set a cookie in vanilla JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true'</span>
</code></pre>
<p>Then when you open the developer console, click "Application" and then on the site under "Cookies", you'll see the cookie you just added:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-101.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you take a closer look at your cookie, you'll see that its expiration date is set to <code>Session</code>. That means the cookie will be destroyed when you close your tab / browser.</p>
<p>That might be the behavior you want, like for an online store with payment information.</p>
<p>But if you want your cookie to last longer, you'll need to set an expiration date.</p>
<h3 id="heading-how-to-set-an-expiration-date-on-a-cookie-in-javascript">How to set an expiration date on a cookie in JavaScript</h3>
<p>To set an expiration date, just set the value of your cookie, then add an <code>expires</code> attribute with a date set sometime in the future:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true; expires=Fri, 26 Feb 2021 00:00:00 GMT'</span> <span class="hljs-comment">// expires 1 week from now</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-102.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>JavaScript's <code>Date</code> object should make this much easier and more flexible. You can read more about the <code>Date</code> object <a target="_blank" href="https://www.freecodecamp.org/news/the-ultimate-guide-to-javascript-date-and-moment-js/">here</a>.</p>
<p>Or you could use the <code>max-age</code> attribute with the number of seconds you'd like your cookie to last:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true; max-age=604800'</span>; <span class="hljs-comment">// expires 1 week from now</span>
</code></pre>
<p>Then when that date rolls around, the browser will automatically remove your cookie.</p>
<h3 id="heading-how-to-update-a-cookie-in-javascript">How to update a cookie in JavaScript</h3>
<p>Whether or not your cookie has an expiration date, updating it is easy.</p>
<p>Just change the value for your cookie, and the browser will automatically pick it up:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"dark_mode=false; max-age=604800"</span>; <span class="hljs-comment">// expires 1 week from now</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-105.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-set-the-path-for-a-cookie-in-javascript">How to set the path for a cookie in JavaScript</h3>
<p>Sometimes you'll only want your cookie to work with certain parts of your website. Depending on how your website is set up, one way to do this is with the <code>path</code> attribute.</p>
<p>Here's how to make it so a cookie only works on the about page at <code>/about</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true; path=/about'</span>;
</code></pre>
<p>Now your cookie will only work on <code>/about</code> and other nested subdirectories like <code>/about/team</code>, but not on <code>/blog</code>.</p>
<p>Then when you visit the about page and check your cookies, you'll see it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-103.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-delete-a-cookie-in-javascript">How to delete a cookie in JavaScript</h3>
<p>To delete a cookie in JavaScript, just set the <code>expires</code> attribute to a date that's already passed:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true; expires=Sun, 14 Feb 2021 00:00:00 GMT'</span>; <span class="hljs-comment">// 1 week earlier</span>
</code></pre>
<p>You could also use <code>max-age</code> and pass it a negative value:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=true; max-age=-60'</span>; <span class="hljs-comment">// 1 minute earlier</span>
</code></pre>
<p>Then when you check for your cookie, it'll be gone:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-104.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And that should be everything you need to know about using cookies in vanilla JS.</p>
<p>Everything we covered will work in a pinch, but if you plan on working with cookies extensively, look into libraries like <a target="_blank" href="https://github.com/js-cookie/js-cookie">JavaScript Cookie</a> or <a target="_blank" href="https://github.com/expressjs/cookie-session">Cookie Parser</a>.</p>
<h2 id="heading-security-concerns-with-cookies">Security concerns with cookies</h2>
<p>In general, cookies are very secure when implemented correctly. Browsers have a lot of built-in limitations that we covered earlier, partly due to the age of the technology, but also to improve security.</p>
<p>Still, there are a few ways that a bad actor can steal your cookie and use it to wreak havoc.</p>
<p>We'll go over some common ways this can happen, and look at different ways to fix it. </p>
<p>Also, note that any code snippets will be in vanilla JavaScript. If you want to implement these fixes on the server, you'll need to look up the exact syntax for your language or framework.</p>
<h3 id="heading-man-in-the-middle-attacks">Man-in-the-middle attacks</h3>
<p>A man-in-the-middle (MitM) attack describes a broad category of attacks where an attacker sits between a client and a server and intercepts the data going between the two.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/man-in-the-middle-attack-how-avoid.png" alt="Image" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://www.netsparker.com/blog/web-security/man-in-the-middle-attack-how-avoid/">Man-in-the-Middle Attacks and How To Avoid Them</a></em></p>
<p>This can be done in a lot of ways: by gaining access to or listening in on an insecure website, mimicking a public WiFi router, DNS spoofing, or through malware / adware like <a target="_blank" href="https://en.wikipedia.org/wiki/Superfish">SuperFish</a>.</p>
<p>Here's a high-level overview of MitM attacks, and how websites can protect themselves and their users.</p>
<p>Warning: The beginning of the video talks about Mary, Queen of Scotts, and shows an animated depiction of her beheading. It's not overly gruesome, but if you'd like to avoid it, skip ahead to <a target="_blank" href="https://youtu.be/8OR2dDIaIDw?t=57">this timestamp</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8OR2dDIaIDw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>As a developer, you can greatly reduce the chance of a MitM attack by ensuring that you enable HTTPS on your server, use an SSL certificate from a trusted certificate authority, and ensure your code uses HTTPS instead of the insecure HTTP.</p>
<p>In terms of cookies, you should add the <code>Secure</code> attribute to your cookies so they can only be sent over a secure HTTPS connection:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=false; Secure'</span>;
</code></pre>
<p>Just remember that the <code>Secure</code> attribute doesn't actually encrypt any data in your cookie – it just ensures that the cookie can't be sent over an HTTP connection.</p>
<p>However, a bad actor could still possibly intercept and manipulate the cookie. To prevent this from happening, you can also use the <code>HttpOnly</code> parameter:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=false; Secure; HttpOnly'</span>;
</code></pre>
<p>Cookies with <code>HttpOnly</code> can only be accessed by the server, and not by the browser's <code>Document.cookie</code> API. This is perfect for things like a login session, where only the server really needs to know if you're signed into a site, and you don't need that information client side.</p>
<h3 id="heading-xss-attacks">XSS attacks</h3>
<p>An XSS (cross-site scripting) attack describes a category of attacks when a bad actor injects unintended, potentially dangerous code into a website.</p>
<p>These attacks are very problematic because they could affect every person that visits the site.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/cross-site-scripting.svg" alt="Image" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://portswigger.net/web-security/cross-site-scripting">Cross-site scripting</a></em></p>
<p>For example, if a site has a comments section and someone is able to include malicious code as a comment, it's possible that every person who visits the site and reads that comment will be affected.</p>
<p>In terms of cookies, if a bad actor pulls off a successful XSS attack on a site, they could gain access to session cookies and access the site as another signed in user. From there, they may be able to access the other user's settings, buy things as that user and have it shipped to another address, and so on.</p>
<p>Here's a video that gives a high-level overview of the different types of XSS – Reflected, Stored, DOM-based, and Mutation:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/EoaDgUgS6QA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>As a developer, you'll want to ensure that your server enforces the Same Origin Policy, and that any input you receive from people is properly sanitized.</p>
<p>And like with preventing MitM attacks, you should set the <code>Secure</code> and <code>HttpOnly</code> parameters with any cookies you use:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=false; Secure; HttpOnly'</span>;
</code></pre>
<h3 id="heading-csrf-attacks">CSRF attacks</h3>
<p>A CSRF (cross-site request forgery) attack is when a bad actor tricks a person into carrying out an unintended, potentially malicious action.</p>
<p>For example, if you're signed into a site and click on a link in a comment, if that link is part of a CSRF attack, it may lead to you unintentionally changing your sign in details, or even deleting your account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/cross-site-request-forgery.svg" alt="Image" width="600" height="400" loading="lazy">
<em>Source: <a target="_blank" href="https://portswigger.net/web-security/csrf">Cross-site request forgery</a></em></p>
<p>While CSRF attacks are somewhat related to XSS attacks, specifically reflected XSS attacks where someone inserts malicious code into a site, each preys on a different type of trust.</p>
<p>According to <a target="_blank" href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">Wikipedia</a>, while XSS "exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser."</p>
<p>Here's a video that explains the basics of CSRF, and gives some useful examples:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/eWEgUcHPle0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>As for cookies, one way to prevent possible CSRF attacks is with the <code>SameSite</code> flag:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">'dark_mode=false; Secure; HttpOnly; SameSite=Strict'</span>;
</code></pre>
<p>There are a few values you can set for <code>SameSite</code>: </p>
<ul>
<li><code>Lax</code>: Cookies are not sent for embedded content (images, iframes, etc.) but are sent when you click on a link or send a request to the origin the cookie is set for. For example, if you're on <code>testing.com</code> and you click on a link to go to <code>test.com/about</code>, your browser will send your cookie for <code>test.com</code> with that request</li>
<li><code>Strict</code>: Cookies are only sent when you click on a link or send a request from the origin the cookie is set for. For example, your <code>test.com</code> cookie will only be sent while you're in and around <code>test.com</code>, and not coming from other sites like <code>testing.com</code></li>
<li><code>None</code>: Cookies will be sent with every request, regardless of context. If you set <code>SameSite</code> to <code>None</code>, you must also add the <code>Secure</code> attribute. It's better to avoid this value if possible</li>
</ul>
<p>Major browsers handle <code>SameSite</code> a bit differently. For example, if <code>SameSite</code> isn't set on a cookie, Google Chrome sets it to <code>Lax</code> by default.</p>
<h2 id="heading-alternatives-to-cookies">Alternatives to cookies</h2>
<p>You might be wondering, if there are so many potential security flaws with cookies, why are we still using them? Surely there must be a better alternative.</p>
<p>These days, you can use either <code>sessionStorage</code> or <code>localStorage</code> to store information that originally used cookies. And for stateful sessions, there's token-based authentication with things like JWT (JSON Web Tokens).</p>
<p>While it may seem like you have to choose between cookie-based or token-based authentication, it's possible to use both. For example, you might want use cookie-based authentication when someone signs in through the browser, and token-based authentication when someone signs in through a phone app.</p>
<p>To muddy the waters a bit more, authentication-as-a-service providers like Auth0 allow you to do both types of authentication.</p>
<p>If you'd like to learn more about web tokens and token-based authentication, check out some of our articles <a target="_blank" href="https://www.freecodecamp.org/news/search/?query=web%20tokens">here</a>.</p>
<h2 id="heading-when-you-give-a-developer-a-cookie">When you give a developer a cookie</h2>
<p>That's it! That should be just about everything you need to know to get started with using cookies, and what to watch out for along the way.</p>
<p>Did you find this useful? How do you use cookies? Let me know over on <a target="_blank" href="https://twitter.com/kriskoishigawa">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
