I have created an auth.js middleware with fastify and prisma but I don't know how to insert it in my route. Here are some examples
const jwt = require("jsonwebtoken");
require("dotenv").config();
module.exports = (request, reply) => {
try {
const token = request.headers.authorization.split(" ")[1];
const decodedToken = jwt.verify(token, process.env.SECRET_TOKEN);
request.token = decodedToken;
} catch (error) {
reply.status(401).send({
message: "Vous êtes pas authentifié",
});
}
};
const profilCtrl = require("../../controller/user");
const auth = require("../../middleware/auth");
async function routes(fastify) {
fastify.get("/profil/:id", profilCtrl.profile);
}
module.exports = routes;
You can add your auth function as a
preHandler
hook like this:or like this:
Looking at your code I'm not totally clear on if it represents multiple files or what exactly is going on. You might want to break it up into separate blocks of code with file names to clarify your question.