Skip to content

Comments

Add authentication rule for Fastify with @fastify/jwt and @fastify/auth#6

Merged
Puppo merged 4 commits intomainfrom
copilot/add-authentication-rule-fastify
Feb 23, 2026
Merged

Add authentication rule for Fastify with @fastify/jwt and @fastify/auth#6
Puppo merged 4 commits intomainfrom
copilot/add-authentication-rule-fastify

Conversation

Copy link
Contributor

Copilot AI commented Feb 20, 2026

New authentication.md rule added to the fastify-best-practise skill covering JWT-based auth and multi-strategy composition.

New rule: rules/authentication.md (HIGH impact)

  • @fastify/jwt plugin setup — shared plugin with authenticate decorator vs. inline token parsing
  • Route protectionpreHandler hook pattern, scoped auth via _hooks.ts with autoload
  • Token lifecycle — login/refresh endpoints with Zod schema validation for request bodies and responses using FastifyPluginAsyncZod
  • Multi-strategy auth@fastify/auth composing JWT + API key strategies
  • TypeScript — module augmentation for decorators and FastifyJWT payload types
  • Testing — authenticated route testing with server.jwt.sign() + inject()

Documentation updates

  • Added Authentication to the rules table in SKILL.md, README.md, and AGENTS.md
  • Updated "Auth/middleware" usage entry in SKILL.md to reference authentication.md
  • Added missing Logging row to README.md and AGENTS.md rules tables

Core pattern

// src/routes/auth/schema.ts
import { z } from "zod";

export const loginBodySchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
});

export const tokenResponseSchema = z.object({
  token: z.string(),
});

// src/routes/auth/index.ts
import { FastifyPluginAsyncZod } from "fastify-type-provider-zod";
import { loginBodySchema, tokenResponseSchema, errorResponseSchema } from "./schema.js";

const authRoutes: FastifyPluginAsyncZod = async function (fastify) {
  fastify.post("/login", {
    schema: {
      body: loginBodySchema,
      response: { 200: tokenResponseSchema, 401: errorResponseSchema },
    },
  }, async (request, reply) => {
    const { email, password } = request.body;
    const user = await verifyCredentials(email, password);
    if (!user) { reply.status(401); return { error: "Invalid credentials" }; }
    const token = fastify.jwt.sign({ id: user.id, role: user.role }, { expiresIn: "1h" });
    return { token };
  });
};

// src/plugins/jwt.ts
import fp from "fastify-plugin";
import fjwt from "@fastify/jwt";

async function jwtPlugin(fastify) {
  await fastify.register(fjwt, { secret: fastify.config.JWT_SECRET });
  fastify.decorate("authenticate", async (request, reply) => {
    try { await request.jwtVerify(); }
    catch { reply.status(401); return reply.send({ error: "Unauthorized" }); }
  });
}

export default fp(jwtPlugin, { name: "jwt", fastify: "5.x" });
Original prompt

Can you generate an authentication rule for Fastify?
I want to use this plugin https://fastify.dev


🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.

@changeset-bot
Copy link

changeset-bot bot commented Feb 20, 2026

🦋 Changeset detected

Latest commit: 248f022

The changes in this PR will be included in the next version bump.

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copilot AI changed the title [WIP] Add authentication rule for Fastify plugin Add authentication rule for Fastify with @fastify/jwt and @fastify/auth Feb 20, 2026
Copilot AI requested a review from Puppo February 20, 2026 06:16
@Puppo Puppo force-pushed the copilot/add-authentication-rule-fastify branch from 38bc51d to 215d6fd Compare February 20, 2026 08:31
Copilot AI and others added 3 commits February 23, 2026 08:23
…th patterns

Co-authored-by: Puppo <2527849+Puppo@users.noreply.github.com>
…ing rules

Co-authored-by: Puppo <2527849+Puppo@users.noreply.github.com>
@Puppo Puppo force-pushed the copilot/add-authentication-rule-fastify branch from 215d6fd to 4a450f2 Compare February 23, 2026 07:29
@Puppo Puppo marked this pull request as ready for review February 23, 2026 07:29
Copy link
Contributor

@Puppo Puppo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot fix the comment

Comment on lines 168 to 196
async function authRoutes(fastify) {
fastify.post("/login", async (request, reply) => {
const { email, password } = request.body;
const user = await verifyCredentials(email, password);
if (!user) {
reply.status(401);
return { error: "Invalid credentials" };
}

const token = fastify.jwt.sign(
{ id: user.id, role: user.role },
{ expiresIn: "1h" },
);
return { token };
});

fastify.post("/refresh", async (request, reply) => {
const { token: oldToken } = request.body;
try {
const payload = fastify.jwt.verify(oldToken);
const newToken = fastify.jwt.sign(
{ id: payload.id, role: payload.role },
{ expiresIn: "1h" },
);
return { token: newToken };
} catch {
reply.status(401);
return { error: "Invalid or expired token" };
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add the Zod schema to the body of the requests and responses?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added Zod schemas for request bodies and responses in the login/refresh endpoints. The section now uses FastifyPluginAsyncZod with separate schema.ts file defining loginBodySchema, refreshBodySchema, tokenResponseSchema, and errorResponseSchema. See commit 248f022.

…ngeset

Co-authored-by: Puppo <2527849+Puppo@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 23, 2026

@copilot fix the comment

Fixed in 248f022 — added Zod schemas to the auth route bodies and responses.

Copilot AI requested a review from Puppo February 23, 2026 07:55
@Puppo Puppo merged commit 72432da into main Feb 23, 2026
3 checks passed
@Puppo Puppo deleted the copilot/add-authentication-rule-fastify branch February 23, 2026 08:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants