Separate back-end and front-end apps on same domain?
I thought of a different solution. I'm going to deploy back-end to a subdomain like
http://api.myapp.example/
and deploy front-end to the main domain:
http://myapp.example/
but I think you'd better use 2 different hosts, one for front-end and one for back-end (I searched the Google and this was the result of my investigations
Indeed its much easier to create a MEAN STACK APP and use one hosting like Heroku for instance. Your frontend is what it is, front end for your backend. It will be easy to access backend / restfulAPI's and frontend like this:
http://localhost:3000/api/contacts
(to access and consume your API endpoint)
http://localhost:3000/contacts
(frontend)
NB: localhost:3000
or http://yourapp.example/api/contacts
(api)
http://yourapp.example/contacts
(frontend)
It's in the URL
You are gonna to dig yourself... deep :)
Simplest and most clean approach with no any doubt is creating a single application serving data for both, BE and FE, where you differ response (JSON vs HTML) by the URL, pseudo routes:
GET /products/:id controllers.Frontend.productHtml(id)
GET /backend/products/:id controllers.Backend.productJson(id)
Benefits:
- single deployment (let's say to Heroku)
- name space managed from one app
- No need to modify the models in many apps after change in one of them
else if
If you're really determined to create a two separate apps, use some HTTP server as a proxy - for an example nginx
- so it will send all requests to domain.tld/*
to application working at port 9000
(which will answer with HTML) but requests to domain.tld/backend/*
redirect to application working at port 9001
responding with JSON.
else
If you are really gonna to response with JSON or HTML depending on the caller you can try to compare headers to check if request was sent from browser or from AJAX call in each controller , but believe me that will become a nightmare faster than you thing... insert the coin, choose the flavor
Other possibility (therefore as separate answer) is using a possibility added in Play 2.1.x
a Content negotiation
I think it's closest for that what you wanted to get initially :)