Home > other >  Next.js API on same server
Next.js API on same server

Time:10-12

Looking at the following scenario, I want to know if this can be considered a good practice in terms of architecture:

  • A React application that uses NextJS framework to render on the server. As the data of the application changes often, it uses Server-side Rendering ("SSR" or "Dynamic Rendering"). In terms of code, it fetches data on the getServerSideProps() function. Meaning it will be executed by the server on every request.
  • In the same server instance, there is an API application running in parallel (it can be a NodeJS API, Python Flask app, ...). This app is responsible to query a database, prepare models and apply any transformation to data. The API can be accessed from the outside.

My question is: How can NextJS communicate to the API app internally? Is a correct approach for it to send requests via a localhost port? If not, is there an alternative that doesn't imply NextJS to send external HTTP requests back to same server itself?

One of the key requirements is that each app must remain independent. They are currently running on the same server, but they come from different code-repositories and each has its own SDLC and release process. They have their own domain (URL) and in the future they might live on different server instances.

I know that in NextJS you can use libraries such as Prisma to query a database. But that is not an option. Data modeling is managed by the API and I want to avoid duplication of efforts. Also, once the NextJS is rendered on the client side, React will continue calling the API app via normal HTTP requests. That is for keeping a dynamic front-end experience.

CodePudding user response:

This is very common scenario when frontend application running independent from backend. Reverse proxy usually help us.

Here are simple way I would like to suggest you to use to achieve(and also this is one of the best way)

  1. Use different port for your frontend and backend application
  2. All api should start with specific url like /api and your frontend route must not start with /api
  3. Use a web server( I mostly use Nginx that help me in case of virtual host, reverse proxy, load balancing and also server static content)

So in your Nginx config file, add/update following location/route

## for backend or api and assuming backend is running on 3000 port on same server
location /api {
    proxy_pass http://localhost:3000;
    ## Following lines required if you are using WebSocket,
    ## I usually add even not using WebSocket
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
} 


## for frontend and assuming frontend is running on 5000 port on same server
location / {
    proxy_pass http://localhost:5000;
}
  • Related