0

I am creating my server the following way:

const createServer = options => {
  const { logSeverity } = options;

  const server = Fastify({
    ignoreTrailingSlash: true
  });


  server.listen(5000, err => {
    if (err) {
      server.log.error(err);
      console.log(err);
      process.exit(1);
    }
  });

  server.register(AutoLoad, {
    dir: path.join(__dirname, "api", "routes")
  });

  server.register(jwt, {
    secret: nconf.get("secrets.jwt")
  });
};

And in one of my modules at ./some/child/path/signToken.js, I do:

const nconf = require("nconf");
const jwt = require("fastify-jwt");

const signToken = payload => {
  fastify.jwt.sign(payload, nconf.get("secrets.jwt"), (err, token) => {
    if (err) throw err;

    const response = {
      userId: payload.user._id,
      username: payload.user.username,
      token
    };

    return response;
  });
};

module.exports = { signToken };

Which throws an error, Cannot read property 'sign' of undefined.

According to the docs,

This will decorate your fastify instance with the standard jsonwebtoken methods

What am I doing wrong here? Is this perhaps not possible because I am creating a server, and server is my fastify instance? Would I then have to import server somehow?

Mike K
  • 7,621
  • 14
  • 60
  • 120

1 Answers1

1

You are starting your server with

server.listen(5000...

Before registering your plugins.

According to the fastify docs the proper order is:

  1. plugins (from the fastify ecosystem)
  2. your plugins (your custom plugins)
  3. decorators
  4. hooks and middlewares
  5. your services

This should happen before calling fastify.listen().

hoekma
  • 793
  • 9
  • 19