0

I receive user related information in the request headers in the express server. I want to access these details in index.js to apply conditional routing based on that parameters.Is there a way to store this runtime variable which will be accessible in index.js or some other way to pass these headers to index.js . I create the build of the src folder using react-scripts build command and server.js uses this folder

server.js

const express = require("express");
const path = require("path");
const app = express(); 
app.use(express.static("build"));

app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
app.listen(5000, () => {
console.log("server started on port 5000");
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css? 
family=Roboto:300,400,500,700|Material+Icons" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" 
/>
<title>sample app</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

index.js

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import User from "layouts/User.js";
import "assets/css/style.css";
const hist = createBrowserHistory();
ReactDOM.render(
 <Router history={hist}>
  <Switch>
    <Route path="/user" component={User} />
    <Redirect from="/" to="/dashboard" />
  </Switch>
 </Router>,
 document.getElementById("root")
 );

1 Answer 1

1

You are trying the wrong way, you cannot pass any information directly from express to react build file, you are sending the file in response. Either you use some template engine like pub, ejs or use some server-side rendering frameworks like nextjs.

And if you really want to this way, you need to

  1. Create API endpoint in express which serves the information, basically the condition you want to.
  2. Create a HOC in react and use that as a parent component to the react-router component

If you are using react 16+, you can use context API instead of HOC

creating a context

import React, {useState, createContext, useEffect} from 'react';

export const ApiContext = createContext();

export const ApiProvider = (props) => {
    const [data, setData] = useState(null);

    useEffect(async () => {
        const getURL = 'http://yourhost';
        const response = await fetch(getURL).json();
        setData(response);
    }, [])

    return (
        <ApiContext.Provider value={[data, setData]}>
            {props.children}
        </ApiContext.Provider>
    );
}

load context

import React, {useContext} from 'react'
import {ApiContext} from './ApiContext'
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import User from "layouts/User.js";
import "assets/css/style.css";
const hist = createBrowserHistory();

const App = (props) => {
    const [data, setData] = useContext(ApiContext)

    //you should have access to both data and setData

    return (
       <Router history={hist}>
        <Switch>
         <Route path="/user" component={User} />
         <Redirect from="/" to="/dashboard" />
        </Switch>
      </Router>
    )
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response.I'm not very clear about the step 2 to create a parent component to react-router component. Can you provide reference or some more explanation on how to do that?
added spinnets according to your requirement, refer this for more info stackoverflow.com/questions/61137644/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.