Search code examples
node.jsreactjsexpressnext.js

How to properly configure Next.js as a frontend and Express app as a backend?


Currently I have create-react-app for frontend and express server for backend. In package.json of my create-react-app I use proxy like this "proxy": "http://localhost:5000". I need to achive the same thing for Next.js app with the same express server.

I just want to be able to use my express server instead of API routes built in Next.js and proxy it like I do in create-react-app.

Do I need to create custom Next.js server even though i'm not changing any of it's functionality? How to do this properly?


Solution

  • yes you have to add custom server in next js

    install express js then add file server.js in root directory of next js project

    const express = require('express')
    const next = require('next')
    const bodyParser = require('body-parser')
    
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dev })
    const handle = app.getRequestHandler()
    
    app.prepare().then(() => {
      const server = express()
    
      server.use(bodyParser.json())
    // add custom path here
    // server.post('/request/custom', custom);
    
      
      server.get('*', (req, res) => {
        return handle(req, res)
      })
    
      server.listen(3000, (err) => {
        if (err) throw err
        console.log('Ready on http://localhost:5000')
      })
    })
    

    after that change package.json file script section

    "scripts": {
        "dev": "node server.js",
        "build": "next build",
        "start": "NODE_ENV=production node server.js",
    }