0

I have this express configuration in the server.js:

  const app = express();
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(crossOriginRequest());
  app.use(setSecurityHttpHeaders());
  app.use(preventMongoOperatorInjection());
  app.use(preventXssAttacks());
  app.listen(80);

How can I set all this middlewares in another file? Example:

  const app = express();
  setBasicMiddlewares(app);
  app.listen(80);

And in setBasicMiddlewares.js (this is an example of what I want, I don't belive it works):

function setBasicMiddlewares(app) {
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(crossOriginRequest());
  app.use(setSecurityHttpHeaders());
  app.use(preventMongoOperatorInjection());
  app.use(preventXssAttacks());
}

export default setBasicMiddlewares;

I'm using node modules with "import" and "export default"

This question is not similar to another question because of the ES6 modules. And the other question is asking about the routes.

Danilo Cunha
  • 1,048
  • 2
  • 13
  • 22
  • Does this answer your question? [How to put middleware in it's own file in Node.js / Express.js](https://stackoverflow.com/questions/14958296/how-to-put-middleware-in-its-own-file-in-node-js-express-js) – FaltFe Sep 03 '20 at 12:15
  • 1
    Consider your use of `export default` -> https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6 – daddygames Sep 03 '20 at 12:25
  • Hi daddygames! I read the question that you send, but my enviroment uses node v14.8, so it does read ES6. I'm wrong to asume that I should use 'export default' (maybe I didn't understand something)? The question that you send it was write 4 years ago. – Danilo Cunha Sep 03 '20 at 14:20
  • FaltFe, this doesn't answer my question because it is not write in ES6, and it does refers to a diferent type of middleware – Danilo Cunha Sep 03 '20 at 14:22
  • app.listen twice is simply not going to work, you should have one entrypoint (index.js, server.js etc), then import/require **routes** which use their own packages etc if need be. – Lawrence Cherone Sep 03 '20 at 14:24

1 Answers1

0

You can separate the creation of your express() instance in another file/module and export it.

app.js

// import dependencies of course

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(crossOriginRequest());
app.use(setSecurityHttpHeaders());
app.use(preventMongoOperatorInjection());
app.use(preventXssAttacks());

module.exports = app;

Then, in your server.js, import your app and setup your server.

server.js

var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000');

This is also the default app structure you get from using express-generator which I would strongly recommend for you.

stvn
  • 1,148
  • 1
  • 8
  • 24