Logo

dev-resources.site

for different kinds of informations.

Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb

Published at
1/13/2025
Categories
node
backend
api
mongodb
Author
brunomestres
Categories
4 categories in total
node
open
backend
open
api
open
mongodb
open
Author
12 person written this
brunomestres
open
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb

Ultimamente tenho utilizado bastante o Fastify em meus projetos pessoais, recentemente descobri diversas funcionalidades através de plugins oficiais.

Eles são leves, eficientes e, o melhor de tudo, encaixam perfeitamente no ecossistema do Fastify.

Então resolvi criar um projeto prático com autenticação e persistência, utilizando o JWT e o MongoDB.

Plugins usados no projeto:

⚒️ O @fastify/jwt é um plugin oficial que simplifica a autenticação com JSON Web Tokens. Com ele, dá pra:

  • Gerar tokens JWT de forma rápida.
  • Verificar tokens automaticamente nas rotas protegidas.

⚒️ @fastify/mongodb: Plugin oficial do Fastify para integração com o banco de dados MongoDB.

  • Ele se encarrega de gerenciar a conexão com o MongoDB de forma eficiente, sem que eu precise ficar configurando drivers manualmente.

Os plugins seguem uma interface padrão. Basta registrá-los com fastify.register(), definir algumas configurações e pronto.

Depois disso posso, acessar o banco diretamente com fastify.mongo e o módulo do jwt com o fastify.jwt.

Também criei um decorator para anexar apenas as rotas que seriam protegidas, onde ele verificará o token passado no cabeçalho.

import Fastify from "fastify";
import mongodb from "@fastify/mongodb";
import jwt from "@fastify/jwt";
import { config } from "./constants.ts";
import * as bcrypt from "bcrypt";

const fastify = Fastify();

type RequestUser = {
  username: string;
  email: string;
  password: string;
};

fastify.register(mongodb, {
  forceClose: true,
  url: config.MONGO_URL,
});

fastify.register(jwt, {
  secret: "supersecret",
});

fastify.post("/signup", async (req, reply) => {
  const salt = 10;
  const { email, password, username } = req.body as RequestUser;

  const data = {
    username,
    email,
    password: await bcrypt.hash(password, salt),
  };

  const user = await fastify.mongo.client.db("plugins").collection("users").insertOne(data);

  reply.send({ user })
});

fastify.decorate("auth", async (request, reply) => {
  try {
    await request.jwtVerify();
  } catch (err) {
    reply.send(err);
  }
});

fastify.post("/signin", (req, reply) => {
  // some code
  const body = req.body;
  const token = fastify.jwt.sign({ body });
  console.log(token);
  reply.send({ token });
});

fastify.get("/", { onRequest: [fastify.auth] }, async (req, reply) => {
  const users = fastify.mongo?.client.db("plugins").collection("users").find();

  const data: any = [];

  for await (const doc of users) {
    data.push(doc);
  }
  return data;
});

fastify.listen({ port: 3333 }, (err) => {
  if (err) process.exit(1);

  console.log("Running server");
});

Enter fullscreen mode Exit fullscreen mode
api Article's
30 articles in total
APIs (Application Programming Interfaces) allow software systems to communicate and exchange data, enabling seamless integrations.
Favicon
Amass API - REST API Solution for Domain Reconnaissance
Favicon
Testing with JWT in .NET APIs
Favicon
Extract structured data using Python's advanced techniques
Favicon
Build and test APIs using simple tools like Postman
Favicon
Pergunte ao especialista - expressões lambda nas biblioteca de APIs
Favicon
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb
Favicon
From Legacy to Modern: Creating Self-Testable APIs for Seamless Integration
Favicon
Unlocking the Power of AWS API Gateway and AWS AppSync: Transforming API Development, Functionality, and Use Cases
Favicon
Effortlessly Host Static JSON Files with JSONsilo.com
Favicon
A Comprehensive Guide to Using OAuth 1.0a with Twitter API v2
Favicon
Understanding Twitter API OAuth 1.0a Authentication: A Comprehensive Guide
Favicon
Top Use Cases of MuleSoft API Manager
Favicon
How to Create and Consume a REST API in Next.js
Favicon
Building a Twitter OAuth Authentication Header Generator with Vercel Serverless Functions
Favicon
GoFr: An Opinionated Microservice Development Framework
Favicon
Latest Trends in AI in 2025
Favicon
What is Spring AI ? Example of a chat API with multiple LLMs
Favicon
Breweries App
Favicon
how to setup express api from scratch
Favicon
Google API to Fetch Favicons for any domain
Favicon
Day 13 of My Android Adventure: Crafting a Custom WishList App with Sir Denis Panjuta
Favicon
Star Wars APIs (SWAPI) 2025
Favicon
Enhance Your WooCommerce Store with SMS and WhatsApp Notifications
Favicon
ArtenoAPI: Translation, Geolocation, QR Codes, and More in One API
Favicon
Interesting feedback on Fuego!
Favicon
Making Beautiful API Keys
Favicon
Your API Doesn’t Always Need to Be a Product
Favicon
Top Blogging Platforms That Support Posting Articles via API
Favicon
How to Post Articles to Dev.to Using iOS Shortcuts
Favicon
Migrando Aplicativos de uma Nuvem para Outra - Parte 3

Featured ones: