Combining frontend and backend services on a single port

I’m working on a project hosted on an AWS Windows EC2 instance. Right now my frontend is accessible on port 80 and the backend runs on port 5000. I’m looking for a way to serve both from the same port without needing to specify a separate port for the API calls.

Currently, it looks like this:

What I want is something like:

Is there a way to set this up using a single server file (like app.js or main.js) that handles both frontend and backend routing? I’m not sure how to configure this properly. Any tips or examples would be really helpful!

Here’s a basic structure I’m thinking of:

const express = require('express')
const app = express()

// Frontend routes
app.get('/', (req, res) => {
  res.send('Welcome to the homepage')
})

// Backend routes
app.get('/api/users', (req, res) => {
  res.json({ users: ['Alice', 'Bob', 'Charlie'] })
})

app.listen(80, () => console.log('Server running on port 80'))

Is this on the right track? How can I improve it to achieve what I’m after?

Your original setup looks promising. However, to merge the frontend and backend on the same port more effectively, consider serving your static files with express.static and mounting your API routes on a separate Router at ‘/api’. This will keep your code organized while keeping the API calls distinct from the content served for the homepage. Additionally, ensure you implement error handling for routes that do not exist, thereby providing a more robust and maintainable application structure.

hey Leo, ur on the right track! u can use express.static to serve ur frontend files and create a separate router for api routes. something like this:

app.use(express.static(‘public’))
app.use(‘/api’, apiRouter)

this way, everything in ur public folder is served at the root, and api calls go to /api. easy peasy!

ooh, that sounds intriguing! have u considered using a reverse proxy like nginx? it could route requests to different services based on the url path. so /api goes to ur backend, and everything else to the frontend. might be worth exploring? what other solutions have u looked into?