Home > Software engineering >  what is use of next() in express js
what is use of next() in express js

Time:08-31

I m using this script to start my next js app, i cant share whole script, but i need to some help to know:

what is use of compression ? what is use of helmet ? what is use of next({dev}) ?

const express = require('express');
const next = require('next');
const helmet = require('helmet');
const compression = require('compression');

const nextApp = next({ dev });
const nextRequestHandler = routes.getRequestHandler(nextApp);

nextApp.prepare()
    .then(() => {
        const server = express();
        server.use(compression());
        server.use(helmet.noSniff());
        server.use(helmet.hsts({ preload: true }));
        server.use(helmet.hidePoweredBy());

        const requestFun = (req, res) => {
            const parsedUrl = parse(req.url, true);
            const { pathname } = parsedUrl;
            //res.setHeader('X-XSS-Protection', '1; mode=block');

            if (pathname === 'xyz' || pathname.startsWith('xyz') || pathname.startsWith('xyz' || pathname.startsWith('/_next'))) {
                const filePath = join(__dirname, '../public', pathname);
                nextApp.serveStatic(req, res, filePath);
            } else {
                nextRequestHandler(req, res, req.url);
            }
        }

        

        

        server.listen(port, (err) => {
            if (err) {
                throw err;
            };
            console.log(`Server started on port ${port}`);
        })
    })
    .catch((ex) => {
        console.error(ex.stack);
        process.exit(1);
    });

CodePudding user response:

  1. Compress is a middleware attempt to compress the request bodies if possible and traverse/pass it through to the next middleware. And Compress will never compress the responses. For more details, you can read all and get to know some extended features of the package using the official docs "https://www.npmjs.com/package/compression"
  2. Helmet is a middleware that helps to send HTTP headers in a more secure way and a helmet is The top-level helmet function is a wrapper around 15 smaller middleware. Please go through it once to get to know that package features in detail "https://www.npmjs.com/package/helmet".
  3. Next is a framework to create node servers specifically for backend applications and next() basically is a method/middleware which requires hostname and port and some optional parameters such as environment to create an instance of next and you can store into a variable "const app = next({ dev, hostname, port })". You can get more detail from the official docs "https://nextjs.org/docs/advanced-features/custom-server".
  • Related