fastify-jwt sign token with user ID payload

2.1k views Asked by At

I'm making a simple sign-in function, that will return a token with the user's ID.

I've registered the fastify-jwt on the fastify instance with the key and added user id in the call to the sign function.

Code auth.js

import Fastify from "fastify";
import fastifyJwt from "fastify-jwt";
import { users } from "../dummy-data/users.js";

const fastify = Fastify();
const SECRET_KEY = "secret";
fastify.register(fastifyJwt, { secret: SECRET_KEY });

......

const signIn = function (req, res) {
  const { email, password } = req.body;
  const foundUser = users.find(
    (user) => user.email === email && user.password === password
  );
  const { id } = foundUser;
  const accessToken = fastify.jwt.sign({ id }, SECRET_KEY);
  res.status(200).send({ accessToken });
}

but this does not work, it shows this error:

"message": "Expected "options" to be a plain object."

{
  "statusCode": 500,
  "error": "Internal Server Error",
  "message": "Expected \"options\" to be a plain object."
}

anyone knows the correct approach?

1

There are 1 answers

0
Evan On

There's no need to pass the SECRET_KEY when signing

const accessToken = fastify.jwt.sign({ id });

because it is already passed to the jwt-plugin when it is registered:

fastify.register(fastifyJwt, { secret: SECRET_KEY });