tsnolan23 / tailor-react-spa

A demo React app using Tailor with common dependencies between fragments
80 stars 33 forks source link

How to handle routing (add more pages) #9

Open rizkysyazuli opened 5 years ago

rizkysyazuli commented 5 years ago

I'm still touching the surface about this whole micro frontend and Tailor thing. But i'm curious on how to handle additional routes / pages with this approach?

FYI, I'm just trying to start a discussion. Does not necessarily need a solution.

armand1m commented 5 years ago

IMO, you should handle routing in Tailor.

You can have your component fragment servers running, and you can create a template for each route of yours and expose them through Tailor.

This gives you flexibility to change fragments on the fly without having to redeploy or change code.

In order to do that, just change the current ./tailor.js with these changes:

'use strict'

const http = require('http')
const Tailor = require('node-tailor')
const tailor = new Tailor({
  templatesPath: __dirname + '/templates'
})

http
  .createServer((req, res) => {
    if (req.url === '/favicon.ico') {
      res.writeHead(200, { 'Content-Type': 'image/x-icon' })
      return res.end('')
    }

    req.headers['x-request-uri'] = req.url
-   req.url = '/index'
+   if (req.url === '/') {
+     req.url = '/index'
+   }

    tailor.requestHandler(req, res)
  })
  .listen(8080, function() {
    console.log('Tailor server listening on port 8080')
  })

(someone please submit a pull request)

Now you can have different templates in the templates folder, one for each route.

When the route is /login, it will render the login.html template, for example.

armand1m commented 5 years ago

Well, it happened that I just found some edge cases too.

For example, let's say I have an application with a Dashboard.

There is a fragment-dashboard and a dashboard.html template for Tailor to render it when I access /dashboard

In this dashboard, there is a menu list of sections in the dashboard you can access.

If I don't care about SSR or URL Sharing, it is just fine to use smth like react-tabs and change content dynamically.

But if I do, I need to include react-router or smth like this to handle different routes inside that specific fragment, so if a user access /dashboard/settings he gets at least redirected to the dashboard settings instead of only rendering the dashboard itself.

I can also decouple my fragment-dashboard into others such as fragment-dashboard-settings and create specific templates for each and tell Taylor to render dashboard-settings.html template whenever a user accesses /dashboard/settings for example.

In this way, I might not need react-router at all.