Performance: Express application structure
This affects the server response time and how quickly the server can handle requests, impacting the time to first byte (TTFB).
const express = require('express'); const app = express(); const userRouter = express.Router(); userRouter.get('/', (req, res) => { res.send('User page'); }); const adminRouter = express.Router(); adminRouter.use((req, res, next) => { // heavy middleware only for admin routes for(let i=0; i<1000000; i++) {} next(); }); adminRouter.get('/', (req, res) => { res.send('Admin page'); }); app.use('/user', userRouter); app.use('/admin', adminRouter); app.listen(3000);
const express = require('express'); const app = express(); app.use((req, res, next) => { // heavy middleware runs on every request for(let i=0; i<1000000; i++) {} next(); }); app.get('/user', (req, res) => { res.send('User page'); }); app.get('/admin', (req, res) => { res.send('Admin page'); }); app.listen(3000);
| Pattern | Middleware Runs | Request Delay | Server Load | Verdict |
|---|---|---|---|---|
| Global heavy middleware | Runs on all requests | Increases TTFB by 50-100ms | Higher CPU usage | [X] Bad |
| Scoped middleware per router | Runs only on relevant routes | Minimal delay on unrelated routes | Lower CPU usage | [OK] Good |
app.js file in an Express application?app.jsapp.js file is the main entry point where the Express server is created and configured.app.js typically containsapp.js is the main server setup file [OK]app.js with frontend filesapp.js only handles databaseapp.js is for authentication onlyapp.js?const express = require('express');express(), so const app = express(); is correct.app.js:
const express = require('express');
const app = express();
app.use('/api', require('./routes/api'));
app.listen(3000);
What happens when a user visits http://localhost:3000/api/users?app.use('/api', ...) behavior./routes/api at the path /api./api/users/api prefix, so it is forwarded to the router in ./routes/api which should handle /users../routes/api -> Option Bconst express = require('express');
const app = express();
app.use((req, res) => {
res.send('');
});
app.get('/home', (req, res) => {
res.send('Welcome Home');
});
app.listen(3000);
Why does visiting http://localhost:3000/home return a blank page?/home is defined with app.get and sends a response.users.js route file inside a routes folder and mount it in app.js?users.jsexpress.Router(), not express() or other calls.app.jsmodule.exports and mounted with app.use('/users', usersRouter);.express.Router() in the route file and proper mounting -> Option CPass the test and this pattern moves unknown