Currently, I have a single Node server that provides both (a) stateless API routes returning JSON, and (b) session-based web routes. My API routes and web routes have started sharing a lot of code, and I'm wondering if and how I can avoid that. I would like to separate the functionality into two servers so the API and web server could be scaled independently.
As an example of code sharing, on the API side, I have defined a path
example.com/api/person/:id/ which returns a user profile as JSON. When the GET request comes in for that path, the API server calls a function
api.getPerson(req, res), which internally calls
Now I also need to create server-generated HTML pages to display user profiles. So I created a web route (e.g. example.com/person/:id) which uses that same
db.getPerson(id) function to query the database.
This works, but the all the routes (API and web) and served from a single server and share some code. This prevents me from scaling the API service and web service independently. For instance, if mobile usage took off, I may need to add allocate an additional stateless API server, but I have no desire to duplicate the session-based web server functionality that is currently bundled with it.
One possible solution might be to separate the existing server into a web server and an API server. Then the web server would access data through the API like any other client.
Is this configuration reasonable?
If so, I'm not exactly sure how to go about it. Is there built-in Node functionality (http.get? http.request?) that is recommended, or are there other solutions to consider?