Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 32 ยท Quality

Security and Common Mistakes

Avoid the common Nuxt security mistakes: XSS with v-html, CSRF, secrets in public config, missing rate limits, client-only auth checks and double fetching.

Nuxt runs your code in two very different places. Code in the browser is controlled by the visitor: they can read it, change it and skip it. Code on the server is yours. Almost every security problem in a Nuxt app comes from forgetting which side something runs on: a secret that ended up in the browser bundle, a permission check that exists only in the page, a form that trusts what it receives.

This lesson goes through the mistakes that show up most often, shows what each one looks like, and gives the fix: escaping and the dangers of v-html, cross-site request forgery (CSRF), secrets in public configuration, rate limiting, security headers, authorization on the server, and the performance bug of fetching twice. Nuxt cannot run on this site, so the Nuxt code is read-only. The runnable examples are Node.js stand-ins that implement the core check of each defense in a few lines, and each says what it simplifies.

Never trust the browser

Input Anything from a request can be forged. Validate it on the server.
Page guards Route middleware only guides navigation. APIs need their own check.
Secrets Public config is public. Keep secrets in server-only config.

The server decides. The browser only asks.

1 / 2

XSS and v-html

Cross-site scripting (XSS) means an attacker gets their JavaScript to run on your page, where it can act as the visitor: read the page, send requests, show fake forms. It happens when untrusted text is inserted into the page as HTML.

Vue protects you by default. Text inside {{ }} is escaped, so a comment containing <script> is displayed as text:

VUE
<template>
  <!-- read-only: safe, shown as plain text -->
  <p>{{ comment.body }}</p>

  <!-- DANGEROUS: inserted as real HTML -->
  <p v-html="comment.body"></p>
</template>

v-html turns the protection off. Use it only for HTML that you control. If you must show user-written rich text, sanitize it with a well-maintained sanitizer library, on the server where possible and before storing or rendering it, and consider a Content Security Policy as a second layer (see the headers section). Related traps are building href values from user input (javascript: URLs run code), and using innerHTML in your own code.

What escaping does

This stand-in compares an escaped and a raw insertion for hostile input. The escape function replaces the five characters that matter in HTML. Vue's own compiler does this for you; the stand-in shows the effect. It does not sanitize HTML: a real sanitizer parses markup and keeps only a safe allow-list of tags and attributes.

Node.js Escaped text versus raw HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the escaped output the < becomes &lt;, so the browser shows the characters instead of creating an element. In the raw output the <img> tag is real, and its onerror handler would run. The last line shows that links need a separate rule, because javascript: URLs bypass text escaping entirely.

Secrets in public configuration

Nuxt's runtimeConfig has two parts. Keys at the top level are private and exist only on the server. Keys under public are sent to every browser. Mixing them up is a classic leak (the full details are in Runtime config and environment variables):

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  runtimeConfig: {
    stripeSecretKey: "",       // private: server only
    public: {
      siteUrl: "",              // public: ships to the browser
      // stripeSecretKey: "",   // WRONG: would be readable by everyone
    },
  },
});

Anything the browser can read, an attacker can read: open the page source or the __NUXT__ payload and it is there. Rules of thumb:

  • Secrets (API keys, database URLs, signing keys) live in private config and are used only in server/ code.
  • A value you would not print on a billboard does not go under public.
  • Do not return whole objects from server routes if they contain private fields (password hashes, internal ids, tokens). Return only the fields the page needs.
  • Do not commit .env files with real values. Rotate any secret that was committed even once.

A scanner for leaks

This stand-in walks a config object and reports any key under public whose name or value looks like a secret. It is a heuristic (it can miss secrets and flag harmless values), so treat it as a model of a lint rule you could run in CI, not as a guarantee.

Node.js Scanning public config for secrets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

It flags apiToken and sessionSecret. It correctly leaves stripePublishableKey alone, since a publishable key is designed to be public, but that is luck of the naming: no scanner replaces knowing what each value is.

Authorization belongs on the server

Route middleware (see Navigation and route middleware) can redirect guests away from /admin. That is good user experience, but it is not a security control, because it runs in the visitor's browser and the API underneath never passes through it. Anyone can call /api/admin/users directly. Every protected server route must verify the session and the permission itself:

TypeScript
// server/api/admin/users.get.ts (read-only)
export default defineEventHandler(async (event) => {
  const session = await requireUserSession(event);   // 401 if not signed in
  if (session.user.role !== "admin") {
    throw createError({ statusCode: 403, statusMessage: "Forbidden" });
  }
  return listUsers();
});

Also check ownership, not only login: when a user requests /api/orders/42, confirm the order belongs to them. Skipping this lets any signed-in user read anyone's data by changing the number in the URL. Forms, validation and auth flows covers sessions in detail.

CSRF: requests the user did not mean to send

Cross-site request forgery tricks a signed-in user's browser into sending a state-changing request to your site from another site, using the user's cookies. Defenses are layered:

  • Set session cookies with sameSite: "lax" (or "strict"), so browsers do not send them with most cross-site requests.
  • Use POST, PUT and DELETE for changes, never GET.
  • For cookie-authenticated APIs, check the Origin header (or Sec-Fetch-Site) against your own site and reject mismatches.
  • Security modules such as nuxt-security offer ready-made protections; check the current documentation for what a version includes.

A stand-in for an origin check, with a rate limiter

The code below is a handler written as a plain function. It has two guards: an Origin check for non-GET requests, and a fixed-window rate limiter per client key. A real server would keep the counters in shared storage (so all instances agree), use the real client address and expire old windows. Here the clock is passed in, which keeps the demonstration deterministic.

Node.js Origin check and rate limiting in a handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The attacker's cross-site POST is rejected with 403, the fourth request from the same address in the same minute gets 429, a different client is unaffected, and the first request of the next minute is served again.

Rate limiting protects logins from password guessing, signup forms from spam and expensive endpoints from abuse. Put the strictest limits on authentication routes. If your app runs behind a proxy or CDN, take the client address from the header your proxy sets, and only trust such headers when the proxy is yours.

Security headers

Headers tell the browser how strictly to treat your pages. Set them in routeRules or with a module, and verify the result with a header checker:

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  routeRules: {
    "/**": {
      headers: {
        "X-Content-Type-Options": "nosniff",
        "Referrer-Policy": "strict-origin-when-cross-origin",
        "X-Frame-Options": "DENY",
        "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
      },
    },
  },
});

The most powerful header is Content-Security-Policy (CSP), which lists where scripts, styles and images may come from, so an injected script cannot run or send data away. It is also the hardest to get right in an app that uses inline scripts (Nuxt adds some for the payload), so adopt it step by step, or let a security module help you generate it, and test in report-only mode first.

The top mistakes, in one list

  • Secrets under runtimeConfig.public, or committed .env files.
  • v-html with user content, or href built from user input.
  • Auth checked only in route middleware, not in server routes.
  • No ownership check on /api/things/:id.
  • Trusting the body: no validation on the server.
  • Returning whole database rows with fields the page does not need.
  • No rate limit on login, signup and password reset.
  • Cookies without httpOnly, secure and sameSite.
  • Verbose errors in production, such as stack traces or SQL in responses.
  • Double fetching, described next. It is not a security bug, but it is the most frequent beginner performance mistake.

Double fetching

If you call $fetch directly in <script setup>, the code runs once on the server while rendering and again in the browser during hydration, so the API gets two requests and the browser may briefly show different data than the HTML had. useFetch and useAsyncData avoid this: the server fetches, puts the result in the payload, and the browser reuses it without a second request (Data fetching with useFetch and useAsyncData has the details).

VUE
<script setup lang="ts">
// read-only
// Mistake: runs on the server AND again in the browser
const bad = await $fetch("/api/profile");

// Better: fetched once, shared through the payload
const { data: profile } = await useFetch("/api/profile");
</script>

Use plain $fetch for actions (clicks, form submissions) and event handlers, as in the earlier lesson on forms.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A comment is shown with {{ comment.body }} and contains <script>alert(1)</script>. What does the visitor see?

    Vue escapes interpolated text, so the angle brackets are displayed as characters instead of becoming an element. Only v-html inserts raw HTML.
  2. 2. Where must permission checks for an admin API run?

    Requests can be sent to the API without visiting any page, so only a check inside the server route reliably applies to every request.
  3. 3. Which runtimeConfig location makes a value readable by every visitor?

    Values under runtimeConfig.public are sent to the browser. Top-level keys stay on the server. A .env file only supplies values, it does not decide visibility.
  4. 4. Which pair of measures best reduces CSRF risk for a cookie-authenticated API?

    SameSite stops browsers from attaching the cookie to most cross-site requests, and checking Origin rejects the ones that still arrive from another site.
  5. 5. Why does calling $fetch at the top of <script setup> often cause a double fetch?

    The setup code runs in both environments, and $fetch does not share its result through the payload. useFetch and useAsyncData do.

Summary

  • Treat everything from the browser as untrusted; validate and authorize on the server.
  • Vue escapes {{ }} output; v-html and user-built href values are the XSS risks, so sanitize or avoid them.
  • Keep secrets in private runtimeConfig and return only the fields a page needs.
  • Route middleware is for navigation. Every protected server route checks the session, the role and the ownership.
  • Use sameSite cookies and Origin checks against CSRF, rate limits on sensitive routes, and security headers (a CSP, introduced gradually).
  • Use useFetch or useAsyncData for page data to avoid double fetching, and $fetch for actions.

Next: Building and deploying Nuxt