Search code examples
reactjsexpressjwttokenexpress-jwt

"JsonWebTokenError: secret or public key must be provided" error


I am new to JWT and Axios, i keep getting the error in the title when i create a post, but login, registeration and password reset work just fine with the token generated on login. Please help,

PostRoutes

router.post("/create-post", userAuth, createPost);

userAuth

const userAuth = async (req, res, next) => {
const authHeader = req?.headers?.authorization;

if (!authHeader || !authHeader?.startsWith("Bearer")) {
next("Authentication== failed");
}

const token = authHeader?.split(" ")[1];

try {
const userToken = JWT.verify(token, process.env.JWT_SECRET_KEY);

req.body.user = {
  userId: userToken.userId,
};

next();
} catch (error) {
console.log(error);
next("Authentication failed");
}

};

createPOST

export const createPost = async (req, res, next) => {
try {
const { userId } = req.body.user;
const { description, image } = req.body;

if (!description) {
  next("You must provide a description");
  return;
}

const post = await Posts.create({
userId,
description,
image,
});


res.status(200).json({
success: true,
message: "Post created successfully",
data: post,
});
}  catch (error) {
console.log(error);
res.status(404).json({ message: error.message });
}
};

Client side/post function

const handlePostSubmit = async (data) => { setPosting(true) setErrMsg("")

try {
  const uri = file && (await handleFileUpload(file));
  const newData = uri ? { ...data, image: uri } : data;

  console.log(newData);



  const res = await apiRequest({
    url: "/posts/create-post",
    token: user?.token,
    data: newData,
    method: "POST",
  });

  console.log(res);

  if (res?.status === 'failed') {
    setErrMsg(res);
  } else {
    reset({
      description: '',
    });
    setFile(null);
    setErrMsg('');
    await fetchPost();
  }
  setPosting(false);

} catch (error) {
  console.log(error);
  setPosting(false);
}

};


Solution

  • The error in your title is saying that it can't find the secret key you provided in the JWT.verify(token, process.env.JWT_SECRET_KEY); function . The issue is in the process.env.JWT_SECRET_KEY part, there might be a typo.Cross check this with your env file and try logging it to console. According to the error its value is null or undefined.