Guide to Setting the "Set-Cookie" Header

Contents

What Does This Header Do?

The Set-Cookie header is used to send cookies from the server to the browser. Cookies can store user session data and other information. Secure attributes, such as HttpOnly, Secure, and SameSite, help prevent common attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).

Steps to Set the Header

1. If You Use a Web Server (e.g., Apache, Nginx, etc.)

For Apache:

  1. Open your website's configuration file (or .htaccess file if you use one).
  2. Add a directive to set cookies with the desired attributes. For example:
    Header set Set-Cookie "sessionId=abc123; HttpOnly; Secure; SameSite=Strict"
  3. Save the file and restart the Apache server to apply changes.

For Nginx:

  1. Open your website's configuration file (e.g., /etc/nginx/sites-available/your-site).
  2. Add a directive to set cookies in the response headers. For example:
    add_header Set-Cookie "sessionId=abc123; HttpOnly; Secure; SameSite=Strict";
  3. Save the file and restart Nginx to apply changes using:
    sudo systemctl restart nginx

2. If You Use a Programming Language:

For PHP:

setcookie("sessionId", "abc123", [
    "httponly" => true,
    "secure" => true,
    "samesite" => "Strict"
]);

For Node.js:

Use a library like cookie-parser or set cookies directly:

res.cookie('sessionId', 'abc123', {
  httpOnly: true,
  secure: true,
  sameSite: 'Strict'
});

For Python (Flask):

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/')
def set_cookie():
    response = make_response("Hello, World!")
    response.set_cookie("sessionId", "abc123", httponly=True, secure=True, samesite='Strict')
    return response

3. Verify the Header

After setting the header, test your website to ensure it’s working:

  1. Open your website in a browser.
  2. Use the developer tools (right-click > Inspect > Network tab) to view the HTTP headers.
  3. Look for the Set-Cookie header with the correct attributes.

Why It Matters

Properly configuring the Set-Cookie header ensures that cookies are secure, reducing the risk of attacks like XSS or CSRF. Attributes such as HttpOnly, Secure, and SameSite are critical for safeguarding user data and maintaining trust.

If you need further assistance, don't hesitate to reach out to your hosting provider or system administrator.