0

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?

jps
  • 20,041
  • 15
  • 75
  • 79
Evan
  • 2,327
  • 5
  • 31
  • 63
  • How is `signIn` used? What is the expected result vs. actual result that makes you say "this does not work"? (From here and according to the documentation, `.sign` method doesn't need the `SECRET_KEY` as a second argument, although indeed the linked JWT specification asks for it.) – Stock Overflaw Aug 30 '21 at 10:10
  • I was confused, because JWT asks for Secret key. I found out `fastify-jwt` don't need SECRET_KEY when assigning. – Evan Aug 30 '21 at 10:13

1 Answers1

1

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 });
jps
  • 20,041
  • 15
  • 75
  • 79
Evan
  • 2,327
  • 5
  • 31
  • 63