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
mongodb Article's
30 articles in total
Favicon
🌐 Building Golang RESTful API with Gin, MongoDB 🌱
Favicon
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb
Favicon
Making a Todo API with FastAPI and MongoDB
Favicon
How to Create and Consume a REST API in Next.js
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
Utilizando la librería Mongoose
Favicon
Full Stack Development (Mern && Flutter)
Favicon
Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries
Favicon
Comprendre le Design Pattern MVC avec Node.js, Express et MongoDB
Favicon
Set up MongoDB primary and secondary with Docker.
Favicon
The Intricacies of MongoDB Aggregation Pipeline: Challenges and Insights from Implementing It with Go
Favicon
Test Post
Favicon
Containerizing a MERN Stack Application!
Favicon
MongoDB vs. Couchbase: Comparing Mobile Database Features
Favicon
6 Steps to Set Up MongoDB Atlas for Node.js Applications
Favicon
MongoDB: How to setup replica sets
Favicon
To Dockerize a Node.js and MongoDB CRUD app
Favicon
Day 39: Deploying Stateful Applications with StatefulSets (MongoDB)
Favicon
Do you think schema flexibility justifies using NoSQL? Think twice.
Favicon
HadiDB: A Lightweight, Horizontally Scalable Database in Python
Favicon
A Simple Guide for Choosing the Right Database
Favicon
Integrating MongoDB Atlas Alerts with Lark Custom Bot via AWS Lambda
Favicon
🔍 MongoDB Data Modeling: Embedding vs. Referencing - A Strategic Choice!
Favicon
Unique Index on NULL Values in SQL & NoSQL
Favicon
Embedding vs. Referencing - A Strategic Choice!
Favicon
Series de tiempo en MongoDB
Favicon
I want to write a code for POS sales output interface - and import to mongoDb for sale analysis- however is POS agnostic interface, should work with all POS
Favicon
Hello,help review my fullstack website stack : nestjs,mongodb and reactjs. https://events-org-siiv.vercel.app/
Favicon
Implementing an Express-based REST API in TypeScript with MongoDB, JWT-based Authentication, and RBAC
Favicon
It's a Security Thing.

Featured ones: