-1

i want to use async await in middleware

but when i use my code this error occure

const refrsh = await User.findOne({ ^^^^^ SyntaxError: await is only valid in async function

how can i fix my code?

this is my code

            exports.authenticateToken = (req, res, next) => {
              const authHeader = req.headers["authorization"];
              const token = authHeader && authHeader.split(" ")[1];
              if (token == null) return res.sendStatus(401);
              jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
                if (err) {
                  const refreshToken = req.body.refreshToken;
                  const refrsh = await User.findOne({
                where: {id:req.body.kakaoid}
                  })
                }
              
                req.user = user;
                next();
              });
            };

3 Answers 3

1

Simply make the (err, user) callback an async function. It should work out alright in this particular case:

exports.authenticateToken = (req, res, next) => {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (token == null) return res.sendStatus(401);
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
    if (err) {
      const refreshToken = req.body.refreshToken;
      const refrsh = await User.findOne({
        where: { id: req.body.kakaoid },
      });
    }

    req.user = user;
    next();
  });
};
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add async when decalre function that you want await:

 jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => { ...

Comments

0

Use async keyword before anonymous callback (err, user) function.

jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
  // your code...
  const refrsh = await User.findOne({
    where: {id:req.body.kakaoid}
  });
 // your code...
});

6 Comments

That's not the right function to make async.
updated the code, ignored the inner function.
The outer function does not need to be async since it doesn't do anything async.
function which is enclosing the await code will be async.
The outer function doesn't need to be async since it only uses callback-based asynchronicity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.