tdudzik
tdudzik

Reputation: 391

Single Page Application - Frontend independent of backend?

I've done some research and I've noticed that in a lot of examples Symfony2/AngularJS apps the frontend and backend are combined; for example, views use Twig.

I'd always thought that it's possible (and common practice) to create the frontend and backend separately and just join them by API. In that case if I want to change a PHP framework I will can do it without any problems and it will be enough to keep API.

So what are the best practices for doing it? It would be great if you could explain it to me and even greater if you just give me a link to good example on github or something.

Upvotes: 14

Views: 9090

Answers (1)

ItalyPaleAle
ItalyPaleAle

Reputation: 7296

We have been developing some projects using the same approach. Not only I think it doesn't have any "side effect", but the solution is very elegant too. We usually create the backend in Node.js, and it is just an API server (not necessarily entirely REST-compliant). We then create another, separate web application for the frontend, written entirely in HTML5/JavaScript (with or without Angular.js). The API server never returns any HTML, just JSON! Not even an index structure.

There are lots of benefits:

  • The code is very clean and elegant. Communication between the frontend and the backend follow standardized methods. The server exposes some API's, and the client can use them freely.
  • It makes it easier to have different teams for the frontend and the backend, and they can work quite freely without interfering with each other. Designers, which usually have limited coding skills, appreciate this too.
  • The frontend is just a static HTML5 app, so it can (and we often did) easily be hosted on a CDN. This means that your servers will never have to worry about static contents at all, and their load is reduced, saving you money. Users are happier too, as CDNs are usually very fast for them.

Some hints that I can give you based on our experience:

  • The biggest issue is with authentication of users. It's not particularly complicated, but you may want to implement authentication using for example protocols like OAuth 2.0 for your internal use. So, the frontend app will act as a OAuth client, and obtains an auth token from the backend. You may also want to consider moving the authentication server (with OAuth) on another separate resource from the API server.
  • If you host the webapp on a different hostname (e.g. a CDN) you may need to deal with CORS, and maybe JSONP.
  • The language you write the backend in is not really important. We have done that in PHP (including Laravel), even though we got the best results with using Node.js. For Node.js, we published our boilerplate on GitHub, based on RestifyJS

I asked some questions in the past you may be interested in:

Upvotes: 15

Related Questions