Bill
Bill

Reputation: 5150

Fastify not defined when trying to sign a jwt with fastify-jwt

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

Upvotes: 0

Views: 1720

Answers (2)

Hannah Nguyen
Hannah Nguyen

Reputation: 69

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()

Upvotes: 0

Fabio
Fabio

Reputation: 21

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.

Upvotes: 2

Related Questions