DEV Community

loading...

How can i keep same backend for mobile app & website ?

uzair004 profile image Muhammad Uzair ・1 min read

what i want :

I want to create website (html, css , js) and its mobile app counterpart (Flutter) with same backend code for both (Express, mongoDB)

I googled :

I get to know about REST API should be used for these kinda stuff. I will create REST API using Express. But

Problem:

REST API only send json data to client and let the client side do whatever it want. But how would i send html documents from server then ?
E.g usually when we visit homepage the server send us index.html (or any template view). If i use REST i would have to send only data not html files then how files will be served by server

Do i have to make separate codes for serving html files & sending data? Then which file will be executed when say node filename.js ?

What about it's mobile app ? How it will get data ?

Discussion (2)

pic
Editor guide
Collapse
eruizdechavez profile image
Erick Ruiz de Chavez

To extend on what @joeczubiak already mention, you could have your website, mobile app, and API as three different codebases, each of them on their own tech stach, whatever makes more sense to you and your project.

For the API, you will need a backend where you can host and run the logic. This can be whatever language, library, etc. you are comfortable writting and/or want to explore.

For the Website, you can think of it as a client that is comsuming the API (just as the mobile app would). Following this approach and, using different tools and frameworks, you can have a moslty static site hosted on a CDN that requires basically no logic on the backend (you can even host it on a CDN).

Finally for the Mobile App, that would abain be build on whatever technology you prefer and consume the API just as the Website will do.

Collapse
joeczubiak profile image
Joe Czubiak

Your Express server can host both your website and your API. It's common to host your API on the same server as your website and just route the API traffic to something like yourdomain.com/api/. This way only the routes under /api will return JSON. You can have all of your necessary endpoints there, /api/users, /api/posts, etc. If you choose to host your website on your Express server, you could pass data down to your views without using the API or use the API via AJAX to fill in your data.

The REST API should not return a whole HTML document but should instead return data that you can put into your HTML.

I would call that method pretty standard, but there are a million ways to go about this. You could also serve your website from somewhere else and use the API to get the necessary data.

For your app, you'll just need to fetch the data from your API. You will also probably want some sort of authentication for your API otherwise anyone could access it because it will be publicly accessible.