2

So I'm working with next.js and a custom server (express.js). I have some middlewares, (f.ex. const attachUser) which I'd like to use in my API endpoints. But for some reason, I am unable to use app.use.

The following code only works, when I don't use app.use(attachUser) and add attachUser to every endpoint manually.

require("dotenv").config();
const express = require("express");
const next = require("next");
const bodyParser = require("body-parser");
const cors = require("cors");

//next.js configuration
const dev = process.env.NODE_DEV !== "production";
const nextApp = next({
  dev
});
const port = 3000;
const handle = nextApp.getRequestHandler();

nextApp.prepare().then(() => {
      const app = express();

      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({
        extended: false
      }));
      app.use(cors());

      const attachUser = (req, res, next) => {
        const token = req.cookies["token"];

        if (!token) {
          return res.status(401).json({
            message: "Authentication invalid"
          });
        }
        const decodedToken = jwtDecode(token);

        if (!decodedToken) {
          return res.status(401).json({
            message: "There was a problem authorizing the request",
          });
        } else {
          req.user = decodedToken;
          next();
        }
      };

      //app.use(attachUser)

      app.get(
        "/api/savedItems", 
        attachUser,       //delete when app.use(attachUser) is used 
        async(req, res) => {
          try {
            //logic
          return res.json(itemData);
        } catch (err) {
          return res.status(400).json({
            error: err
          });
        }
      });

Can someone tell me what I'm doing wrong?
Btw, this is my first project. Any suggestions to improve code are appreciated! Thanks a lot!

1 Answer 1

0

You can't write code between a "try {}" and a "catch{}" and aditionally a useless ";" after "try{}". You can use a JS lint tool for checking code

2
  • You mean line 52? There is a catch in line 54.
    – Ewax_Du
    Commented Jan 23, 2021 at 16:43
  • yeah, I missed that. That semicolon and "return res.json(itemData);" is disturbing Commented Jan 24, 2021 at 1:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.