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!