1.0.0 • Published 1 year ago

@chmking/nuxt-csrf v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Nuxt CSRF

CSRF support for Nuxt

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install @chmking/nuxt-csrf h3

Add to modules in nuxt.config.ts:

// nuxt.config.ts
export default defineNuxtConfig({
    modules: [ '@chmking/nuxt-csrf' ]
})

Peer Dependency

This package has a peer dependecy on H3 ~v0.7.21 which fixes an issue when an H3 event body is read twice.

Usage

Get Token

This module makes the token available through a composable:

<script setup lang="ts">
const token = useCSRFToken();
</script>

Form

<template>
  <div>
    <form method="POST" action="/api/test">
      <input name="_csrf" type="hidden" :value="token" />
      <input type="submit" value="Submit" />
    </form>
  </div>
</template>

<script setup lang="ts">
const token = useCSRFToken();
</script>

AJAX

<template>
  <div>
    <button @click="onClick">Submit</button>
  </div>
</template>

<script setup lang="ts">
const token = useCSRFToken();

function onClick() {
  $fetch("/api/test", {
    method: "POST",
    body: {
      _csrf: token.value,
    },
  });
}
</script>

Options

Currently Nuxt CSRF only supports cookies for CSRF secret storage.

Cookies

Nuxt CSRF can be configured with the cookie options from @chmking/h3-csrf.

Default:

{
  cookie: {
    domain: '',
    httpOnly: true,
    name: '_csrf',
    path: '/',
    sameSite: 'lax',
    secure: false,
  },
}

Environment Override

In support of 12 factor app principles, environment overrides are available for cookie config.

This will override the modules config in nuxt.config.ts.

  • NUXT_CSRF_COOKIE_DOMAIN
  • NUXT_CSRF_COOKIE_HTTP_ONLY
  • NUXT_CSRF_COOKIE_MAX_AGE
  • NUXT_CSRF_COOKIE_NAME
  • NUXT_CSRF_COOKIE_PATH
  • NUXT_CSRF_COOKIE_SAME_SITE
  • NUXT_CSRF_COOKIE_SECURE

In a production environment with the server running on HTTPS a more secure config is:

NUXT_CSRF_COOKIE_SAME_SITE="strict"
NUXT_CSRF_COOKIE_SECURE="true"

Development

You can develop locally with the playground:

  • Run npm run dev:prepare to generate type stubs.
  • Use npm run dev to start playground in development mode.

License

Distributed under the MIT License. See LICENSE for more information.

1.0.0

1 year ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago