Post(s) tagged Express

Next.js create a custom server with HTTP proxy to external server

First, create a server file named server.js and paste the below code to that file.

const next = require('next');
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost';
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
var express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

app.prepare().then(() => {
    const server = express();
    server.use('/api', createProxyMiddleware({ target: 'https://samprix.com', changeOrigin: true, }));    

    server.all('*', (req, res) => handle(req, res));

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
})

Then build the Next.js using the below command

NODE_ENV=production next build

After the build run the server js file using the below command

NODE_ENV=production node -r esm node server.js

For more information about the Next.js custom server refer to this doc.


66 Views Posted on March 04, 2022
SPONSORS