3

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 db.getPerson(id) to look up a person in the database. The API is accessed by a single-page Javascript app and soon a mobile app and it works fine.

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?

  • 2
    You need to provide a bit more detail about your API calling mechanism, as it is not clear from your question what "my web server calls API functions directly" means. – Robert Harvey Jan 13 '15 at 23:56
  • Robert, I've attempted to clarify. Please let me know if it's still unclear or you have any questions. – Lorenz Forvang Jan 14 '15 at 1:02
  • 1
    This question may help: programmers.stackexchange.com/questions/256600/… – David Scholefield Jan 14 '15 at 7:53
  • David, thanks for the link. I suppose that's essentially what I have now -- the API route callback function api.getPerson(req, res) and the web route callback function web.getPerson(req, res) can both share the "linking library" that contains db.getPerson(id). I think I just need to put more care into packaging this linking library so I can easily maintain it as a single codebase and share it across my API and web servers. – Lorenz Forvang Jan 14 '15 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.