Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 32 ยท Projects

Project: a dashboard with auth

Build a Nuxt dashboard with a login endpoint, session cookie, route middleware guard, protected API and a chart data endpoint, with Node stand-ins.

A dashboard is a private page that shows live numbers to people who have signed in. It looks simple, but it is where the most important security rule of web development appears: hiding a page is not protection, protecting the data is. If a visitor can read your API without logging in, a route guard that merely redirects them in the browser has achieved nothing.

In this project you build the full chain: a login endpoint that sets a session cookie, route middleware that guards the pages, a protected API that checks the session itself, and a data endpoint for a chart. It builds on Navigation and route middleware, Server routes and the Nitro engine and Forms, validation and auth flows.

Real or stand-in? The Nuxt code below is real and read-only, because this site cannot run a Nuxt server. The two runnable examples are Node.js stand-ins: one runs the whole session flow (login, cookie, protected data, logout) as plain functions, and the other turns raw events into the series a chart needs. For production, a maintained authentication module is usually better than hand-written session code, and this lesson says where that choice matters.

The auth chain

Login Check the password, create a session.
Cookie The browser sends the session id back.
Page guard Route middleware redirects visitors.
API guard Every protected endpoint checks the session.

The API guard is the one that really protects data.

1 / 2
sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /dashboard (no cookie)
    S-->>B: redirect to /login
    B->>S: POST /api/auth/login (email, password)
    S-->>B: 200 + Set-Cookie session
    B->>S: GET /api/stats (cookie)
    S->>S: look up session
    S-->>B: chart data

The session id travels in a cookie. The server looks the session up on every protected request.

Step 1: sessions on the server

A session is a record on the server that says "this random id belongs to this user". The browser stores only the id, in a cookie. For the project, sessions live in a Map, which is fine for one server process but is lost on restart and not shared between servers. In production, use Nitro's storage layer with Redis or a database (Server middleware, plugins and utils), or a module that manages sessions for you.

TypeScript
// server/utils/session.ts (read-only)
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'
import type { H3Event } from 'h3'

interface User {
  id: number
  email: string
  passwordHash: string // "salt:hash", both in hex
}

const users: User[] = [
  { id: 1, email: '[email protected]', passwordHash: hashPassword('correct horse') },
]

const sessions = new Map<string, { userId: number; expires: number }>()
const TTL_MS = 1000 * 60 * 60 * 8

export function hashPassword(password: string): string {
  const salt = randomBytes(16)
  return salt.toString('hex') + ':' + scryptSync(password, salt, 32).toString('hex')
}

export function verifyPassword(password: string, stored: string): boolean {
  const [saltHex, hashHex] = stored.split(':')
  const expected = Buffer.from(hashHex, 'hex')
  const actual = scryptSync(password, Buffer.from(saltHex, 'hex'), 32)
  return timingSafeEqual(expected, actual)
}

export function findUserByEmail(email: string) {
  return users.find((u) => u.email === email.trim().toLowerCase())
}

export function startSession(event: H3Event, userId: number) {
  const id = randomBytes(32).toString('hex')
  sessions.set(id, { userId, expires: Date.now() + TTL_MS })
  setCookie(event, 'session', id, {
    httpOnly: true,
    secure: !import.meta.dev,
    sameSite: 'lax',
    path: '/',
    maxAge: TTL_MS / 1000,
  })
}

export function endSession(event: H3Event) {
  const id = getCookie(event, 'session')
  if (id) sessions.delete(id)
  deleteCookie(event, 'session', { path: '/' })
}

export function getUser(event: H3Event) {
  const id = getCookie(event, 'session')
  const session = id ? sessions.get(id) : undefined
  if (!session || session.expires < Date.now()) return null
  return users.find((u) => u.id === session.userId) ?? null
}

export function requireUser(event: H3Event) {
  const user = getUser(event)
  if (!user) throw createError({ statusCode: 401, statusMessage: 'Not signed in' })
  return user
}

Four details matter here. Passwords are never stored: only a salted hash made with scrypt, a deliberately slow function. The session id is 32 random bytes, which cannot be guessed. The cookie is httpOnly (page scripts cannot steal it) and sameSite: 'lax' (it is not sent on most cross-site POST requests). And requireUser is one small function every protected route calls, so the check cannot be forgotten by accident in a hand-written if.

Step 2: the login endpoint

TypeScript
// server/api/auth/login.post.ts (read-only)
export default defineEventHandler(async (event) => {
  const body = await readBody<{ email?: string; password?: string }>(event)

  if (typeof body?.email !== 'string' || typeof body?.password !== 'string') {
    throw createError({ statusCode: 400, statusMessage: 'Email and password are required' })
  }

  const user = findUserByEmail(body.email)
  // Same message for "unknown email" and "wrong password", so attackers learn nothing.
  if (!user || !verifyPassword(body.password, user.passwordHash)) {
    throw createError({ statusCode: 401, statusMessage: 'Invalid email or password' })
  }

  startSession(event, user.id)
  return { user: { id: user.id, email: user.email } }
})

Two rules are worth copying into every login endpoint. Give the same error for a wrong email and a wrong password. And limit how often one address can try: login endpoints are the favorite target of password-guessing bots (Security and common mistakes).

The first stand-in runs the whole flow with plain functions and a fake request object. It prints cookie attributes but not the session id, because that value is random.

Node.js The whole session flow as plain functions

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.

Read the output from top to bottom. The first stats request fails with 401 because there is no cookie. Both wrong logins return the same message, so nobody can use the form to find out which emails exist. After a good login, the cookie flows through the "browser" automatically and the stats request works. After logout the session is deleted on the server, so the same cookie value would no longer work even if someone had copied it.

Step 3: the guard for pages

Route middleware runs before a page is shown. It asks the server who the visitor is and redirects to the login page when the answer is "nobody".

TypeScript
// server/api/auth/me.get.ts (read-only)
export default defineEventHandler((event) => {
  const user = getUser(event)
  return { user: user ? { id: user.id, email: user.email } : null }
})
TypeScript
// app/middleware/auth.ts (read-only)
export default defineNuxtRouteMiddleware(async (to) => {
  // During server rendering, forward the visitor's cookie to our own API.
  const headers = useRequestHeaders(['cookie'])
  const { user } = await $fetch('/api/auth/me', { headers })

  if (!user) {
    return navigateTo('/login?redirect=' + encodeURIComponent(to.fullPath))
  }
})
VUE
<!-- app/pages/dashboard.vue (read-only) -->
<script setup lang="ts">
definePageMeta({ middleware: 'auth' })

const { data: stats } = await useFetch('/api/stats/visits', {
  headers: useRequestHeaders(['cookie']),
})
</script>

The forwarded cookie header is the detail people forget. When the page is rendered on the server, the request to /api/auth/me is made by the server itself, not by the browser, so it has no cookie unless you pass it along. Without it, every server render would think the visitor is signed out and redirect them, even right after logging in.

The login page uses the redirect query value to send people back to where they came from. Never redirect to whatever the query says: accept only local paths that start with a single /, or an attacker can craft a login link that sends users to a fake site afterwards.

VUE
<!-- app/pages/login.vue (read-only) -->
<script setup lang="ts">
const route = useRoute()
const email = ref('')
const password = ref('')
const error = ref('')

function safeTarget(value: unknown): string {
  const target = typeof value === 'string' ? value : '/dashboard'
  return target.startsWith('/') && !target.startsWith('//') ? target : '/dashboard'
}

async function submit() {
  error.value = ''
  try {
    await $fetch('/api/auth/login', { method: 'POST', body: { email: email.value, password: password.value } })
    await navigateTo(safeTarget(route.query.redirect))
  } catch (e: any) {
    error.value = e?.statusMessage ?? 'Login failed'
  }
}
</script>

<template>
  <form @submit.prevent="submit">
    <input v-model="email" type="email" autocomplete="username" required />
    <input v-model="password" type="password" autocomplete="current-password" required />
    <button>Sign in</button>
    <p v-if="error" role="alert">{{ error }}</p>
  </form>
</template>

Step 4: the protected API and chart data

Every endpoint that returns private data calls requireUser first. Even if somebody skips your pages and requests the URL directly, they get a 401.

TypeScript
// server/api/stats/visits.get.ts (read-only)
export default defineEventHandler((event) => {
  requireUser(event)

  const { days } = getQuery(event)
  const count = Math.min(Math.max(Number(days) || 7, 1), 30)

  // Replace this with a database query that groups events by day.
  const labels: string[] = []
  const values: number[] = []
  for (let i = count - 1; i >= 0; i--) {
    const d = new Date(Date.now() - i * 86400000)
    labels.push(d.toISOString().slice(5, 10))
    values.push(100 + ((d.getUTCDate() * 37) % 60))
  }
  return { labels, values }
})

The endpoint returns two plain arrays, which most chart libraries accept. It clamps days to a safe range, because a query parameter is untrusted input. The page can feed labels and values to any chart component; load the chart library on the client only, for example inside a <ClientOnly> wrapper, so server rendering never touches browser-only code (Hydration and SSR pitfalls).

The second stand-in does the data work of such an endpoint: it groups raw events into per-day totals, fills days with no events with zero, clamps the range and draws the result as text bars.

Node.js From raw events to a chart series

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 empty day (03-03) appears as 0, which matters: a chart that skips missing days draws a misleading line. The clamping lines show how a hostile or sloppy days value is handled without an error.

What a module would add

Hand-written sessions teach the idea, and they are enough for a small internal tool. For a real product, a maintained authentication module is usually the better choice: it handles encrypted cookies, session storage, OAuth providers, CSRF protection and edge cases you will not think of. Nuxt has several (search the module list for the one that fits your login method). The pattern stays the same as in this lesson: the server checks the session, and middleware only improves the experience.

Ideas to extend the project

  • Role-based access: store a role on users and add requireRole(event, 'admin').
  • Rate-limit the login route and lock accounts after repeated failures.
  • Keep sessions in Redis through the storage layer so restarts do not log everyone out.
  • Add a /logout button that calls the logout endpoint and then navigateTo('/login').
  • Cache heavy statistics with defineCachedEventHandler per user.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must every protected API route check the session itself even when a route middleware guards the page?

    A route guard only controls navigation in the app. The data is protected only if the API verifies the session on every request.
  2. 2. Why does the login endpoint return the same error for an unknown email and a wrong password?

    A single generic message gives attackers no information about which accounts exist.
  3. 3. What does the httpOnly flag on the session cookie do?

    An httpOnly cookie is sent with requests but is invisible to document.cookie, which limits the damage of an XSS bug.
  4. 4. Why does the page middleware call useRequestHeaders(['cookie']) before fetching /api/auth/me?

    On the server, $fetch to an internal route has no browser cookies. Forwarding the cookie header lets the API see who is asking.
  5. 5. How should the login page use the ?redirect= value after a successful login?

    Redirecting to an arbitrary URL is an open redirect that attackers use for phishing. Accept only local paths.

Summary

  • A session is a server-side record. The browser holds only a random id in an httpOnly, sameSite cookie.
  • Store password hashes made with a slow, salted function such as scrypt, and compare them in constant time.
  • Route middleware guards pages for a good experience. A requireUser check in each API route guards the data.
  • Forward the cookie header with useRequestHeaders when server-rendered code calls your own API.
  • Accept only local redirect targets, clamp query values, and return the same message for wrong emails and wrong passwords.
  • For real products, prefer a maintained auth module over hand-written session code.

Next: Project: a notes app with a server API