I have an Express app serving a front-end web app.
How do I create an API server with /api as its root? I would like to separate the API concerns from the main app.
I have an Express app serving a front-end web app.
How do I create an API server with /api as its root? I would like to separate the API concerns from the main app.
There are likely to be considerations over the intensity of connections to your API. That will be one of the leading factors in determining whether you really need a separate server.
In answer to your domain query, there are npm packages available to assist in creating an api subdomain if thats suitable https://api.example.com
, but assuming it's a small to medium sized application, you'll be fine to use Express Router to achieve what you want. Details are here in the docs.
app.use('/api', router);
This will apply a filter to all requests so that only those with /api
will reach this router like:
https://www.example.com/api/users/1
In fact, there could be an argument against prematurely optimising your app and building a second server. That said, if you modularise your code base suitably, then it should be a breeze to transfer the api routes over to a new server later down the line.
There is no best way. It all depends on how you want to do it. You can create an express router and mount it or create an express server instance and mount. See details here