0

In my handler I want to be able to sign a JWT but 'fastify' is not defined.

const postJoinHandler = async (
  request: any,
  reply: any
): Promise<{ id: string; name: string }> => {
  try {
    const { username, password } = request.body;
    const token = fastify.jwt.sign({ username, password }); //<=== Fastify not defined
    return reply.code(201).send(token);
  } catch (error) {
    request.log.error(error);
    return reply.send(400);
  }
};

my Schema...

import { postJoinHandler } from '../handlers/auth';

const Token = {
  type: 'object',
  properties: {
    username: { type: 'string' },
    password: { type: 'string' },
  },
};


const postJoinSchema = {
  schema: {
    body: {
      type: 'object',
      required: ['username', 'password', 'email', 'fullname'],
      properties: {
        name: { type: 'string' },
        password: { type: 'string' },
      },
    },
    response: {
      201: Token,
    },
  },
  handler: postJoinHandler,
};

export { postJoinSchema };

And my route

import { FastifyPluginAsync } from 'fastify';
import { postJoinSchema } from '../schemas/auth';

const auth: FastifyPluginAsync = async (fastify): Promise<void> => {
  fastify.post('/auth/join', postJoinSchema);
};

export default auth;

I've got fastify-jwt loaded as a plugin

const fp = require('fastify-plugin');

module.exports = fp(async function (fastify: any) {
  fastify.register(require('fastify-jwt'), {
    secret: 'Supersecret!@#',
  });

  fastify.decorate('authenticate', async function (request: any, reply: any) {
    try {
      await request.jwtVerify();
    } catch (err) {
      reply.send(err);
    }
  });
});

docs here

Bill
  • 4,614
  • 13
  • 77
  • 132

2 Answers2

2

you can access your fastifyinstance via the request. Just do request.server. The server is the fastifyinstance where you can access your plugins and so on.

Fabio
  • 21
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 17 '22 at 01:15
0

thanks a lot for your answer. I have the same problem here is my answer as well: //verify password const isAuth = verifyPassword(request.body.password, foundUser.password);

if (isAuth) {
  const { password, salt, ...rest } = foundUser;
  console.log("rest", rest);
  // generate access token
  return { accessToken: request.server.jwt.sign(rest) };
}

so instead of calling fastify.jwt.sign(), you need to use request.fastify.jwt.sign()