We’ve now set up the CSRF middleware on the backend and generated a CSRF token that will be stored on the cookie. In order to actually validate whether a token is valid, we need to make sure the CSRF token from the client is automatically submitted with the contents of the form. It is common practice to place the CSRF token as a hidden
<input> field within a form.
The name of the hidden
<input> should be named
_csrf in order for the
csurf module to extract the token value when the form is submitted.
We can use EJS templating syntax to set the value of the hidden
<input> to the CSRF token secret. We do that by using the property name of the object that is passed into the
A complete form example with CSRF protection looks similar to:
<form action="/submit" method="POST"> <input type="hidden" name="_csrf" value="<%= csrfToken %>" /> <label for="body">Enter message: </label> <input id="body" name="message" type="text" /> <input type="submit" value="Submit" /> </form>
Now, the CSRF token will be sent with the form data on submission.
csurf will extract the CSRF token that is passed and compare it to the token that the server created. If the token value does not match, then CSURF will return an error.
Inside the form in form.js, add an
<input> tag with
type equal to
Press the Check Work button to check your work after each checkpoint.
Set the hidden
<input> name to
Set the hidden
<input> value to the CSRF token stored in the variable named
csrfToken that is passed from app.js using EJS templating syntax.