'jwt.sign() i get error:0909006C:PEM routines:get_name:no start line depending on the options

const jwt = require("jsonwebtoken");  

jwt.sign(user.dataValues, process.env.JWT_SECRET, {
    algorithm: "RS256",
    expiresIn: "14 days",
  });

leads to Error: error:0909006C:PEM routines:get_name:no start line at Sign.sign (node:internal/crypto/sig:131:29)

jwt.sign(user.dataValues, process.env.JWT_SECRET, {
    //algorithm: "RS256",
    expiresIn: "14 days",
  });

works perfectly fine

the setup:
Operating System: Mac OS
Node v17.0.1

"dependencies": {
  "apollo-server": "^3.4.0",
  "apollo-server-core": "^3.4.0",
  "dotenv": "^10.0.0",
  "fs": "^0.0.1-security",
  "google-auth-library": "^7.10.1",
  "graphql": "^15.6.1",
  "jsonwebtoken": "^8.5.1",
  "nodemon": "^2.0.14",
  "pg": "^8.7.1",
  "sequelize": "^6.7.0"
},


Solution 1:[1]

RS256 stands for RSASSA-PKCS1-v1_5 using SHA-256, that means it uses a digital signature generated using a private RSA key. Your process.env.JWT_SECRET is either a string or a buffer that is not a private RSA key in PEM format, ergo Node's crypto module fails to parse it as such. That's the error you're seeing.

When you remove the algorithm option the library automatically chooses an algorithm based on your "secret" input, in this case - a symmetric secret, HS256 will be used instead (and is the documented default).

Solution 2:[2]

This error says that there is an error with the format of the keys you provided. The PEM format needs the lines

-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----

in a line of their own surrounding your key. Adapt for private keys.

If I have to take a guess, you most likely forgot this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Filip Skokan
Solution 2 skytreader