How to serve both client and server applications on the same port

I’m working with an AWS EC2 Windows server that currently serves my web application on port 80 and my API server on port 5000. I want to combine both services to run on a single port so users don’t need to specify different ports when accessing my API endpoints.

Current setup:

Client app: mysite.com
API server: mysite.com:5000

Desired setup:

Client app: mysite.com
API endpoints: mysite.com/api/

Is it possible to create one main server file that handles both static file serving for the frontend and API routing for the backend? I’m looking for guidance on structuring this in a single application file.

Yes, it’s definitely possible to serve both static files and API routes on a single port. This approach is commonly used and can simplify the user experience by not requiring different port specifications. You can set up your server to differentiate between API calls and static file requests based on the URL path. For instance, you could configure your routing to handle requests to /api/ as API endpoints and all other requests as static file serving. Most popular web frameworks offer middleware to facilitate this configuration. On your AWS EC2 Windows instance, ensure that your route handlers prioritize API routes first, so any matching paths are routed accordingly, while all other requests fall back to static file serving. This setup not only streamlines your application but also enhances usability for your users.

sounds good, but what framework are u using? express, koa, something else? also, have u thought about routing conflicts? what if someone tries to hit /api as a static file path?

totally agree! just do app.use('/api', apiRoutes) for your api stuff and app.use(express.static('public')) for your frontend. it runs smooth on one port, been using this on my ec2 without any issues.