Skip to content

Cookies

In the Ad Serving section, I mentioned that serving ads to the right user is the key. However how do we know which user is the right one? Cookie is one of the ways to retrieve the information. Cookies are small data files that are stored on a user's device by a website. Here is a simple example of how cookie works.

Site A is a news site, when you visit the site, a cookie adtech_uid=sample_cookie is set in your browser. After visiting Site A, you visit Site B, the browser will automatically send the cookie to the server as long as the site is in the same domain. Through this cookie, the server can know that you are the same user who visited Site A.

js
import http from 'http';

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);

  if (url.pathname === '/site-a') {
    res.writeHead(200, {
      'Content-Type': 'text/html',
      'Set-Cookie': 'adtech_uid=sample_cookie; Path=/; Max-Age=31536000'
    });
    return res.end(`
      <h1>Welcome to Site A (News Site)</h1>
      <p>An AdTech cookie has been silently planted in your browser right now.</p>
    `);
  }

  if (url.pathname === '/site-b') {
    const receivedCookie = req.headers.cookie || "No cookie received 😢";

    res.writeHead(200, { 'Content-Type': 'text/html' });
    return res.end(`
      <h1>Welcome to Site B (Shoe Store)</h1>
      <p>The browser sent this cookie to the server:</p>
      <pre style="background: #eee; padding: 10px; font-weight: bold; color: red;">
        Received Cookie: ${receivedCookie}
      </pre>
    `);
  }

  res.writeHead(404);
  res.end();
});

server.listen(3000, () => {
  console.log('STARTING SERVER ON PORT 3000');
});

Run the demo:

bash
node code/site.js

Then open http://localhost:3000/site-a followed by http://localhost:3000/site-b.

After while, the server accumulated the data of each user and can know the user's interest and behavior. So, now when you serve ads to this user, you can serve the ads that are more likely to be interested in.

The example is a bit simplified. In reality, when a user visits a site with a tracking pixel or a script from advertiser, the ad server will set the cookie in the browser. The ad server and the site the user visited are often in different domains, this is called 3rd party cookie. After setting this cookie, the ad server can track the user's behavior and serve ads to the user based on the user's interest and behavior.