JWT Authentication: Login and Refresh
Access token + refresh token flow, httpOnly cookies, silent refresh with interceptors.
JWT Authentication: Login and Refresh is a free Vue Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Access and Refresh Token Model
A robust JWT scheme uses two tokens: a short-lived access token (minutes) sent with every API request, and a long-lived refresh token (days) used only to mint new access tokens. This limits exposure if an access token leaks.
Registering the JWT Plugin
With Fastify, register @fastify/jwt and provide a strong secret. It adds signing and verification helpers to the app and request objects.
import jwt from '@fastify/jwt'
await app.register(jwt, {
secret: process.env.JWT_SECRET
})The Login Route
POST /auth/login validates credentials, then issues both tokens. Never store plaintext passwords — compare against a hash (bcrypt/argon2).
app.post('/auth/login', async (req, reply) => {
const { email, password } = req.body
const user = await findUser(email)
if (!user || !(await verifyHash(password, user.hash))) {
return reply.code(401).send({ error: 'Invalid credentials' })
}
// ... sign tokens (next scene)
})Signing the Access Token
Sign a short-lived access token with the user id and minimal claims. Keep the expiry short (e.g. 15 minutes).
const accessToken = app.jwt.sign(
{ sub: user.id, role: user.role },
{ expiresIn: '15m' }
)Signing the Refresh Token
Sign a long-lived refresh token with a distinct payload marker (or a separate secret). It is used solely at the refresh endpoint.
const refreshToken = app.jwt.sign(
{ sub: user.id, type: 'refresh' },
{ expiresIn: '7d' }
)Refresh Token in an httpOnly Cookie
Store the refresh token in an httpOnly, SameSite, Secure cookie. JavaScript cannot read it (mitigating XSS theft), and the browser sends it automatically to the refresh endpoint.
reply.setCookie('refreshToken', refreshToken, {
httpOnly: true,
sameSite: 'strict',
secure: true, // HTTPS only
path: '/auth/refresh',
maxAge: 60 * 60 * 24 * 7
})Returning the Access Token in the Body
The access token is returned in the JSON response body. The Vue app keeps it in memory (not localStorage) and attaches it to API requests. The refresh token never appears in the body.
return reply.send({
accessToken,
user: { id: user.id, name: user.name }
})
// refreshToken is only in the httpOnly cookieWhy Not Store Access Tokens in localStorage
localStorage is readable by any script, so an XSS bug can steal a token there. Keeping the access token in JS memory and the refresh token in an httpOnly cookie reduces the blast radius of XSS.
The Refresh Route
POST /auth/refresh reads the refresh token from the cookie, verifies it, and issues a new access token. It returns the fresh access token in the body.
app.post('/auth/refresh', async (req, reply) => {
const token = req.cookies.refreshToken
if (!token) return reply.code(401).send()
try {
const payload = app.jwt.verify(token)
const accessToken = app.jwt.sign(
{ sub: payload.sub }, { expiresIn: '15m' }
)
return reply.send({ accessToken })
} catch {
return reply.code(401).send({ error: 'Invalid refresh' })
}
})Protecting Routes
Add a preHandler that verifies the access token from the Authorization header. @fastify/jwt's request.jwtVerify() throws on invalid/expired tokens, returning 401.
app.get('/api/me', {
preHandler: async (req, reply) => {
try { await req.jwtVerify() }
catch { reply.code(401).send({ error: 'Unauthorized' }) }
}
}, async (req) => getProfile(req.user.sub))Logout: Clearing the Cookie
Logout clears the refresh cookie so it can no longer mint access tokens. For stronger guarantees, also track/revoke refresh tokens server-side (a denylist or rotation).
app.post('/auth/logout', async (req, reply) => {
reply.clearCookie('refreshToken', { path: '/auth/refresh' })
return reply.send({ ok: true })
})Quick Check
Test your understanding of JWT auth.
Recap
You learned JWT login and refresh:
- Short-lived access token + long-lived refresh token
POST /auth/loginvalidates credentials and signs both- Refresh token goes in an httpOnly SameSite Secure cookie
- Access token returns in the body and lives in JS memory
POST /auth/refreshmints a new access token from the cookie
Frequently asked questions
Is the “JWT Authentication: Login and Refresh” lesson free?
Yes — the full text of “JWT Authentication: Login and Refresh” is free to read here on the web, and the Vue Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.
What will I learn in “JWT Authentication: Login and Refresh”?
Access token + refresh token flow, httpOnly cookies, silent refresh with interceptors. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vue Academy?
No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “JWT Authentication: Login and Refresh” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vue Academy lesson?
Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Fastify Backend for Vue SPAs
- JWT Authentication: Login and Refresh
- Authenticated API Calls with Axios Interceptors
- Deploying Full-Stack Vue to Production