Skip to content

Latest commit

 

History

History
200 lines (161 loc) · 8.53 KB

fastify.md

File metadata and controls

200 lines (161 loc) · 8.53 KB

Fastify integration

Prerequisites and scope

The view snippets assume @fastify/view is already configured with Nunjucks and that your view files exist; registering consent does not provide reply.view(). Each security recipe replaces or extends registration, rather than registering consent a second time. Combine selected options and register consent once. The Fastify example is a runnable alternative that renders Nunjucks directly without @fastify/view.

npm install govuk-analytics-consent fastify fastify-plugin @fastify/view nunjucks govuk-frontend
# Optional security middleware used below:
npm install @fastify/helmet @fastify/cookie @fastify/csrf-protection @fastify/rate-limit

See the options reference for callback contracts. COOKIE_SECRET in the CSRF recipe must contain a host-provided signing secret; use HTTPS and secure cookies in production.

Registration and views

Install the package and the adapter's optional dependencies, then set GTM_CONTAINER_ID=GTM-XXXXXXX:

npm install --save fastify fastify-plugin
import Fastify from 'fastify'
import consentPlugin from 'govuk-analytics-consent/fastify'

const app = Fastify()

await app.register(consentPlugin, {
  serviceName: 'Apply for a licence',
  tags: ['google-analytics']
})

app.get('/', (request, reply) => reply.view('index.njk', {
  govukAnalyticsConsent: request.govukAnalyticsConsentContext
}))

Fastify view plugins do not provide universal locals, so pass request.govukAnalyticsConsentContext to each view. The plugin registers the consent routes and parses URL-encoded consent forms; if a form parser is already registered, it reuses it. Configure your view plugin with govukAnalyticsConsentTemplatePath() and GOV.UK Frontend's templates in the Nunjucks search paths. Extend govuk-analytics-consent/template.njk instead of govuk/template.njk for automatic head markup, noscript fallback, banner, and browser script:

{% extends "govuk-analytics-consent/template.njk" %}
{% block pageTitle %}Apply for a licence{% endblock %}
{% block content %}<h1 class="govuk-heading-xl">Apply for a licence</h1>{% endblock %}

If your view overrides head, bodyStart, or bodyEnd, call super() to retain consent content. In a custom GOV.UK template, import the macros from govuk-analytics-consent/macro.njk: add govukAnalyticsConsentHead to head before analytics scripts, govukAnalyticsConsentNoscript and govukAnalyticsConsentBanner to bodyStart, and govukAnalyticsConsentScripts to bodyEnd. Replace an existing cookie banner instead of rendering two. See the Fastify server and example views, or the template guide for full block and macro examples.

Content Security Policy

Create the consent object before CSP registration and pass the same object to both plugins. Register @fastify/helmet before consent. consent.helmetCsp merges GTM and configured tag sources into your Helmet directives:

import Fastify from 'fastify'
import helmet from '@fastify/helmet'
import consentPlugin from 'govuk-analytics-consent/fastify'
import { createGovUkAnalyticsConsent } from 'govuk-analytics-consent'

const app = Fastify()
const consent = createGovUkAnalyticsConsent({ tags: ['google-analytics'] })

await app.register(helmet, {
  enableCSPNonces: true,
  contentSecurityPolicy: {
    directives: consent.helmetCsp({
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],
      styleSrc: ["'self'"],
      connectSrc: ["'self'"],
      imgSrc: ["'self'"],
      frameSrc: ["'self'"]
    })
  }
})

await app.register(consentPlugin, consent)

The adapter reads reply.cspNonce.script when Helmet's nonce generation is enabled. Pass that same value as cspNonce in your view context; do not read it back from the consent context. To provide your own nonce source, set getNonce: (request) => ...; that callback takes precedence. The package does not set CSP headers itself. For other CSP libraries, use consent.csp or the exported mergeCspDirectives, toBlankieCsp, and toHelmetCsp helpers. Tags configured only in GTM may need additional sources. Nonces avoid 'unsafe-inline', and the GTM bootstrap propagates its nonce to the remote script.

CSRF protection

The consent POST is not protected automatically. Register the cookie and @fastify/csrf-protection plugins before consent. The form token is in the parsed request body, so validate in preValidation, not onRequest:

import Fastify from 'fastify'
import cookie from '@fastify/cookie'
import csrfProtection from '@fastify/csrf-protection'
import consentPlugin from 'govuk-analytics-consent/fastify'

const app = Fastify()

await app.register(cookie, { secret: process.env.COOKIE_SECRET })
await app.register(csrfProtection, {
  cookieOpts: { signed: true, path: '/', httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production' }
})
app.addHook('preValidation', (request, reply, done) => {
  if (request.method === 'POST' && request.url.split('?')[0] === '/govuk-analytics-consent/consent') {
    app.csrfProtection(request, reply, done)
  } else {
    done()
  }
})

await app.register(consentPlugin, {
  getCsrfFormFields: async (_request, reply) => ({
    _csrf: await reply.generateCsrf()
  })
})

The hook validates the consent POST before its handler without blocking GET requests that generate tokens. Adjust the path if you change routePrefix. Alternatively, use verifyCsrfFormSubmission with your own token verification function; returning false sends a 403. Do not shared-cache HTML with request-specific tokens. Keep the signing secret outside source control and use HTTPS in production.

Rate limiting

Rate limiting complements CSRF protection but does not replace it. Install @fastify/rate-limit and register it before consent:

import rateLimit from '@fastify/rate-limit'
import consentPlugin from 'govuk-analytics-consent/fastify'

await app.register(rateLimit, { max: 120, timeWindow: '1 minute' })
await app.register(consentPlugin)

This sets a per-client limit on routes registered after the limiter. Use route-specific configuration or a shared Redis store when the wider app needs a different policy. The package itself does not impose a limit.

Consent state and cookies page

Handlers can read request.govukAnalyticsConsent, which exposes state, hasChoice, and isCategoryAccepted(categoryId). request.govukAnalyticsConsentContext holds the view model:

app.get('/recommendations', (request, reply) => {
  const template = request.govukAnalyticsConsent.isCategoryAccepted('personalization')
    ? 'recommendations.njk'
    : 'recommendations-without-personalization.njk'
  return reply.view(template, { govukAnalyticsConsent: request.govukAnalyticsConsentContext })
})

Mount a cookies-page route and render govukAnalyticsConsentCookiesPage(govukAnalyticsConsent) in its content block. Set cookiesPageUrl: '/cookies' to link to it from the banner. See the cookies-page example and cookie configuration. For per-request language selection and host translators, see Localisation.

Integration checklist

  1. Configure your view engine and static GOV.UK assets. Choose CSP and CSRF plugins appropriate for your application, in the same Fastify scope as consent and the page routes.
  2. Register Helmet, cookie/CSRF plugins, and any rate limiter before consent. Validate form tokens in preValidation after parsing; do not require CSRF tokens on GET pages. Host i18n must be available by consent's preHandler hook.
  3. Register consent once. State is available from onRequest; the rendered context is available from preHandler. Pass request.govukAnalyticsConsentContext explicitly to each view.
  4. Pass Helmet's script nonce as the separate cspNonce view local. Extend the package template or add its macros without duplicating the banner. Mount /cookies and set cookiesPageUrl.
  5. With CSRF enabled, verify a missing-token consent POST returns 403 and a valid form POST returns 303 with a consent cookie. With CSP enabled, script nonces must match the header and browser tools must show no CSP violations.
  6. Test JavaScript-disabled form submission and different request languages. Do not shared-cache nonce- or token-bearing HTML. See Development for local checks.