When configuring csurf
using app.use
, the functions and values are available on all Express get
, post
, and all
routes. The middleware function is configured at the application level and will be called on each request so we won’t have to explicitly pass it to each route.
The csurf
module provides the req.csrfToken()
function to create a CSRF token. When the CSRF token secret is generated, it is passed to the client in the response and stored as a persistent cookie.
We can pass an object as a second argument to the render()
function allowing the EJS
template engine to use the CSRF token in the DOM of the client’s browser.
A CSRF token can be sent to an EJS template similar to:
app.get('/form', (req, res) => { res.render('formTemplate', { csrfToken: req.csrfToken() }); });
If you’d like to run the application, type node app.js
into the bash Terminal and then refresh the mini browser.
Instructions
Inside the route to '/'
, pass an object to the render()
function with a property named csrfToken
.
Set the value to the CSRF token generated using thecsrfToken()
method.
Press the Check Work button to check your work.