DEV Community

Muhammad Uzair
Muhammad Uzair

Posted on

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

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)

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.