I am implementing a JWT generator for my backend but when using the fastify way I get this error:
Cannot read properties of undefined (reading 'sign')
so here I am stuck.
Somebody would know the reason for this, I attach fragments of my code.
import fetch from "node-fetch";
import { randomBytes, createHash } from "crypto";
import { PrismaClient, users } from ".prisma/client";
import { Jwt, JwtPayload } from "jsonwebtoken";
import HttpsProxyAgent from "https-proxy-agent";
const proxyAgent = HttpsProxyAgent("http://148.201.1.200:3128");
const fastify = require('fastify')()
function genRandomString(length) {
return randomBytes(Math.ceil(length)).toString("hex").slice(0, length);
}
function generateJWTToken(user: users) {
const { password, sal, active, ...enviar } = user;
const token = fastify.jwt.sign({
...enviar,
});
console.log(token);
const decoded: Jwt = fastify.jwt.decode(token, { complete: true });
return {
token,
uuid: user.id,
nombre: `${user.name} ${user.lastname_p} ${user.lastname_m}`,
exp: (decoded.payload as JwtPayload).exp,
};
}
main.ts
async function main() {
app.register(require("@fastify/swagger"), swaggerOptions);
app.register(require('@fastify/jwt'), {
secret: 'supersecret'
})
app.decorate("prisma", prisma);
app.register(require("@fastify/cors"), {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "Accept"],
});
app
.register(authRouterWeb, {
prefix: "/api/v1/auth-web",
});
app.listen(port, (err, address) => {
if (err) {
app.log.error(err);
process.exit(1);
}
app.log.info(`server listening on ${address}`);
});
}
so, please if you have any suggestion or another alternative to change that or improve my code ill be grateful.