GitHub

Guides

Handling CSRF

1. Install and configure the @adonisjs/shield addon

npm install --save @adonisjs/shield
node ace configure @adonisjs/shield

Note

Find out more about @adonisjs/shield in the AdonisJS documentation.


2. Create the CsrfMiddleware that adds the token to head meta and globals

// app/Middleware/Csrf.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'


export default class CsrfMiddleware {
  public async handle({ request, radonis }: HttpContextContract, next: () => Promise<void>) {
    radonis
      .withHeadMeta({ 'csrf-token': request.csrfToken })
      .withGlobals({ csrfToken: request.csrfToken })


    await next()
  }
}

3. Register the newly created CsrfMiddleware

// start/kernel.ts
Server.middleware.register([() => import('App/Middleware/Csrf')])

4. Define the type for the csrfToken global

// contracts/radonis.ts
declare module '@microeinhundert/radonis-types' {
  interface Globals {
    csrfToken?: string
  }
}

5. Create a React hook for retrieving the token from globals (Optional)

// resources/hooks/useCsrfToken.ts
import { useGlobals } from '@microeinhundert/radonis'


export function useCsrfToken() {
  const { csrfToken } = useGlobals()
  
  return csrfToken
}

6. Create a React component for the hidden _csrf form field (Optional)

// resources/components/CsrfField.tsx
import { useCsrfToken } from '../hooks/useCsrfToken'


function CsrfField() {
  const csrfToken = useCsrfToken()


  return csrfToken 
    ? <input name="_csrf" type="hidden" value={csrfToken} /> 
    : null
}


export default CsrfField
Previous
useRenderer