Catalog My learning Blog
Backend for Frontend (BFF) Course with Node and Fastify · Phase 2 · Lesson 8 · 6 min read

CSRF Protection for a BFF: Custom Header Defense

On this page
  1. The attack cookies invite
  2. SameSite helps, but isn't enough alone
  3. The custom header defense
  4. Test the defense like an attacker
  5. Add an Origin check
  6. Keep GET requests safe
  7. What about anti-forgery tokens?
  8. Check yourself

The attack cookies invite

Cookies solved token theft, but they bring back an old problem. The browser attaches cookies to requests no matter which page started them. If Ada is signed in to TaskBoard and visits a malicious site, that site can try to make *her* browser send a request to TaskBoard, cookie included. This is cross-site request forgery (CSRF).

The classic version is a hidden form that submits itself:

HTML
<class="tok-k">form method="POST" action="https://app.taskboard.dev/api/tasks" enctype="text/plain">
  <class="tok-k">input name='{"title":"pwned","x":"' value='"}'>
</class="tok-k">form>
<class="tok-k">script>document.forms[0].submit()</class="tok-k">script>

The text/plain trick makes the body look like JSON. A careless API that doesn't check the content type would create the task.

RFC 10017 is direct about it: the BFF MUST implement a proper CSRF defense.

SameSite helps, but isn't enough alone

Day 4's SameSite attribute already blocks the cookie on cross-*site* POSTs, whether it's Lax or Strict. Why do more?

  • Same-site isn't same-origin. blog.taskboard.dev and app.taskboard.dev are the same *site*. If any subdomain is compromised or taken over (a forgotten DNS record pointing at a deleted cloud resource is a common way), its pages count as same-site and the cookie goes along. RFC 10017 says SameSite is only sufficient if the BFF is never same-site with any other application.
  • Lax still allows top-level GET navigations. Any GET route that changes state is exposed.
  • Some deployments need SameSite=None, for example when the app is embedded in another site.

The custom header defense

RFC 10017's recommended defense uses a rule that browsers enforce strictly. A cross-origin request with a custom header is not a "simple request", so the browser first sends a CORS preflight (OPTIONS) asking permission. If the BFF doesn't answer with CORS headers allowing that origin, the browser never sends the real request.

So the BFF requires a fixed header on every API call, and the app always sends it:

JavaScript
// BFF: one hook covers /api, /bff and /auth/logout
app.addHook('onRequest', async (req, reply) => {
  const needsCheck = req.url.startsWith('/api/') || req.url.startsWith('/bff/') || req.url === '/auth/logout';
  if (needsCheck && req.headers['x-csrf'] !== '1') {
    return reply.code(403).send({ error: 'csrf' });
  }
});
Shell
// React app: one fetch wrapper used for every BFF call
export function bff(url: string, init: RequestInit = {}) {
  return fetch(url, {
    ...init,
    headers: {
      'x-csrf': '1',
      ...(init.body ? { 'content-type': 'application/json' } : {}),
      ...init.headers,
    },
  });
}

The header's *value* isn't a secret. The protection comes from the fact that an attacker's page can't add it without a preflight that your BFF will refuse. The RFC adds one requirement: the BFF MUST check that *every* request carries it. One forgotten route is a hole, which is why the check lives in a global hook rather than in each handler.

The BFF must also not enable CORS for other origins. No Access-Control-Allow-Origin, and certainly not a reflected origin with credentials.

Test the defense like an attacker

The lab ran an attacker page on a different site, http://127.0.0.1:4950, while Ada was signed in to the BFF at http://localhost:4900:

Code
same-origin fetch without x-csrf:                403
cross-site fetch with x-csrf (credentials):      blocked: Failed to fetch   (preflight refused)
cross-site form POST, text/plain:                403 {"error":"csrf"}
tasks after attacks:                             0

The cross-site fetch never reached the API, because the preflight failed. The forged form arrived without the header and was refused. Even a request from TaskBoard's own origin was refused when it lacked the header, which catches mistakes in your own code too.

Write these as automated tests against your BFF. They're cheap and they stop a regression from shipping quietly.

Add an Origin check

Browsers send an Origin header on cross-origin requests and on all POSTs. Checking it costs one line and gives a second, independent layer:

JavaScript
const ALLOWED_ORIGIN = 'https://app.taskboard.dev';

app.addHook('onRequest', async (req, reply) => {
  const origin = req.headers.origin;
  if (req.method !== 'GET' && req.method !== 'HEAD' && origin && origin !== ALLOWED_ORIGIN) {
    return reply.code(403).send({ error: 'bad origin' });
  }
});

Some privacy tools strip Origin, so treat a *missing* header as allowed and rely on the custom header for those. A *wrong* origin is always refused.

Keep GET requests safe

All of this assumes GET requests don't change anything. A route like GET /bff/tasks/42/delete defeats most CSRF defenses, because a plain link or an image tag can trigger it. Use POST, PUT, PATCH or DELETE for every change, including logout.

What about anti-forgery tokens?

The older defense puts a random token in the page and a cookie, and compares them on each request. It works, and RFC 10017 accepts it when your framework provides it. But it needs the token delivered to the page and sent with every call, and it's easy to get subtly wrong. For a BFF serving its own single-page app, the custom header plus no CORS is simpler and just as strong.

TipUse the same bff() wrapper for every call in the React app, and lint against raw fetch to BFF paths. Then the header is never forgotten, and the BFF's 403 tells you immediately if it is.

Check yourself

A custom header turns the request into a non-simple one, so the browser first sends a CORS preflight asking the BFF for permission. The BFF never allows other origins, so the browser refuses to send the real request. In the lab, the attacker's fetch failed with Failed to fetch before reaching the BFF.

A compromised or taken-over subdomain, such as a forgotten DNS record pointing at a deleted cloud resource, counts as the same site, so the browser sends the cookie with its requests. Any state-changing GET route is also exposed under Lax, because top-level GET navigations carry the cookie.

An attacker only needs one unprotected route that changes data. Checking in each handler means one forgotten handler is a hole, while a global hook covers every route automatically, including ones added later. RFC 10017 states the BFF must check that every request carries the header.

Both would have. Cross-site POSTs don't carry a Lax cookie, and the missing header made the BFF answer 403 before checking the session. Layered defenses mean one misconfiguration, such as switching to SameSite=None, doesn't open a hole.

Some privacy tools strip Origin, so rejecting missing headers would break legitimate users, and the custom header still protects those requests. A wrong Origin means a browser told you the request started on another site, which is never legitimate for this BFF.