What is a Nonce?

In the previous CSRF for Web Developer I mentioned one security solution is generating a CSRF Token, which is actually a type of Nonce.

Nonce = number used once

A nonce is a value used only once and can take any form: a number, a string, an incrementing counter, a timestamp… The key is to verify “each operation must be unique” — nonces are used wherever important actions are involved.

  • API security
  • Web login
  • Blockchain
  • Browser protections

OTP Nonce

Suppose an OTP implementation sends a one-time password to a user; when the user submits it and the OTP is marked as used to prevent replay attacks, making the same OTP record unusable again — in this context the OTP is a nonce.

DBServerUserDBServerUserCreate OTP (verify=false)Send OTPSubmit OTPQuery OTP verify statusverify=falseUpdate verify=trueUpdate successVerification successful

How CSP Uses Nonce

The browser Content Security Policy also uses nonces to prevent malicious JavaScript from executing. When a site enables CSP, it can specify a set of nonces via script-src, and only <script> tags with the matching nonce are allowed to run.

Content-Security-Policy: script-src 'nonce-r4nd0m123';
<script nonce="r4nd0m123"> console.log("Trusted script"); </script>

How Race Conditions Break a Nonce’s One-time Guarantee

The core value of a nonce is that it can “only be used once”, but that property isn’t guaranteed merely by producing a random value — it depends on how the backend verifies and marks its usage state.

If there’s a time gap between “checking whether it’s been used” and “marking it as used”, an attacker can resend the request during that window and potentially have the same nonce accepted multiple times, resulting in a replay attack.

Summary

Think of a nonce as a single-use ticket that ensures an event has a unique (fresh) lifecycle.

Further Reading