How to separate the frontend routing from backend endpoints? - javascript

I have an express server which handle some routes
/users/login
/users/register
/orders/add
and so on..
serving a static files, in the default route
"/"
so, if user navigated to domain.com for example
it will navigate to that static files
these static files are a react frontend app
the default url "/" will navigate to a login page
and "/dashboard" will navigate to another page
what actually happen, is there's kind of conflict between the backend and frontend routes
for example
if user navigated to "/dashboard"
the expected result is to navigate him to the frontend page
what actual happen is "the backend handle that route not the frontend" and simply return : "I don't have that route (404)
What was in my mind is to navigate any not handled route to the frontend
using that code
app.get('*', async function (request, reply) {
return reply.sendFile('index.html')
})
however, not solved my problem

Related

How to run middleware on each React page in express server

I'm running an express server and if no other certain URLS aren't met, the user is redirected to the React App:
app.get("*", verify, (req, res) => {
if (maintenance) {
return res.sendFile("./maintenance.html", { root: __dirname });
}
return res.sendFile(
path.resolve(__dirname, "../frontend/build", "index.html")
);
});
This successfully runs the verify middleware needed to check if the user making the request is logged in, if not it redirects them to another service for them to login.
I would've thought that since all URLS that are being used are going through the whole web app is going through this express server, the verify middleware would've been executed no matter what page the user is on. However, this middleware is only executed upon either opening the site on a browser that hasn't been to the site yet (not cached) or if the user force refreshes the page.
I'm new to React and this has led me to believe that React loads the whole app, and upon each change of page (for example from /home to /profile) it doesn't change the url, just loads the portion of the app that's already loaded and so no matter what page the user is on, express will always see that the user is only on the root domain.
How would I get pass this without doing any of this logic on the frontend side. E.g. run the verify function before each page on the react app is loaded into view
Since React is all client side rendering you will need to handle that middleware in your React router, not your Node router. On the frontend we call this "middleware" protected routes.
The overall point is, you will need to protect those routes on the frontend, as when you change a page in React, Node does not know about it (because React is client side rendered).

What is relationship between Express routes and client routes in NextJS?

I'm a NextJS newbie and trying to understand the relationship between routes defined in Express and those defined in the 'client', React portion of NextJS. Specifically, if one defines a route on the Express side, such as
router.get("/aLonelyRoute",(req,res)=> {
res.end("You made it!")
})
that doesn't have a corresponding 'page' on the client side (we have the following pages in our React app
pages/index.js
pages/something.js
pages/another.js
), if a request is made to /aLonelyRoute from the browser, will this always be served from the Express server, never rendered from the client?
Also, is it true that if the Express server serves a page that *does *correspond to a route reflected on the 'client' side, then app.render automagically serves it either from the server or renders it from the client, depending:
router.get("/something",(req,res)=> {
app.render(req,res,'something',query)
})
Am I on the right path in understanding this?
You use express for a custom SSR(Server Side Rendering). - In a simple way when you refresh the page or type the URL in url bar and press enter. Express and Next.js router work together to serve the page however it depends on what kind of render has been asked for. if it is a Client side rendering, then next.js will take over and if SSR, then Express will take over first(Next.js will ask for express to take over).
server.get('/p/:id', (req, res) => {
const actualPage = '/post'
const queryParams = { title: req.params.id }
app.render(req, res, actualPage, queryParams)
})
In above example, if there is a client side rendering, user will go something like /post/a-cool-post but server will receive /post?id=a-cool-post which was masked to /p/a-cool-post. Note that /p/... doesn't exists. it is a mask URL. look at as in this example.
<Link as={`/p/${post.id}`} href={`/post?title=${post.title}`}>
<a>{post.title}</a>
</Link>
Long story short, it means we are asking express (in this case server side rendering) if a route is something like /p/a-cool-post, go and give us /post/a-cool-post which is a client side rendering. so the route in client and server will be the same.
First question:
/aLonelyRoute is only in express and there is no code to tell what is it equivalent in client-die. so it will only render from Server.
Second question:
Yes it is correct. Depends what user ask for, if they type url in url bar and press enter
and refresh the page, then express and if you use Next Router for routing, then it will be client side.

React with Adonis

I am trying to integrate React with Adonis Js to build an SPA. Adonis handles routing to an SPA by
Route.any('*', function * (request, response) {
yield response.sendView('home')
})
I have done exactly that in app > Http > routes.js
Then I created a home.njk in resources > views to act as the landing page for my application. Now, I have a react file where I have created a footer. I want to handle all the links in the footer with React-router. React router handles urls to navigate to a page. However, the above code(in Adonis) says that any url (*) is going to render 'home'. That is exactly what is happening.
How do get around it? Thanks!
You should define your api routes before the route *.
Adonis Router will go through your routes.js file and get the first route that match.

Koa w/client side router

Current situation:
frontend: React & React-Router
backend: Koa
app.use(mount('/graphql', graphqlHTTP({ schema: schema })));
app.use(mount('/api', api));
app.use(serve(__dirname + '../../public')); //serves static index.html
When I click on React Router's < Link > in the browser, every webpages shows.
Whenever I refresh the page or manually enter a link. I get a 'not found' page. There is no server side rendering going here by the way. How do I let React-Router handle routes not specified above, i.e. only on the client?
The server has to respond with something when the page is refreshed; in this case, it needs to respond with index.html so that the client-side application can boot, and then React Router can mount the right component based on the URL.
So, server-side, you need to tell Koa to serve index.html for every URL that doesn't already match any of the other routes.
Solution (based on the answer above)
import router from 'koa-router';
import sendfile from 'koa-sendfile';
//code to initialize router
//...
router.get('*', function* () {
let stats = yield* sendfile.call(this, pathToIndexHtml));
if (!this.status) this.throw(404)
})
Koa now serves index.html on every route that isn't specified. :)

Combining Different Modules in NodeJs

I have Created Separate Working Modules in nodejs
Login
Chat
File sharing.
I want to combine them all. Like after getting successful login i want it to redirect to chat module. Right now i can redirect to static html page after login.
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
Note: Now If i have to run any module i have to compile it individually and run it on localhost.
Assuming that you are using Express Framework, for the successRedirect , instead of redirecting the user to '/profile' route, redirect him to (lets say) '/chat' and define the app.get('/chat,callback) route in the same file , or export your chat module and require it in the file that you are using for authentication/login

Categories

Resources