I am following this tutorial in my nextjs
app for adding a new middleware for logging so I have the following code in my server.js:
// create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
// setup the logger
server.use(morgan('combined', { stream: accessLogStream }))
And it is working without a problem.
But I want to have the logic in a separate file in the middleware directory so I have :
middlewares/logger/index.js
import morgan from "morgan";
import fs from 'fs';
import path from 'path';
export default (req, res, next) => {
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
return morgan('combined', { stream: accessLogStream });
};
and in my server.js I will have: (after importing and initializing stuff)
server.use(logger);
server.use(othermiddlewareone);
server.use(othermiddlewaretwo);
The other middlewares are working fine but this one breaks. Do you know why is that?
I changed the middleware like this and now it is working fine :)
import type { Request, Response, Next } from './types';
import morgan from "morgan";
import fs from 'fs';
import path from 'path';
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'server.log'), { flags: 'a' })
const logger = morgan('combined', { stream: accessLogStream })
export default async (req: Request, res: Response, next: Next) => {
logger(req, res, function (err) {
return next();
})
};