Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
How do I send a variable from Express.js backend to React.js frontend?

I am trying to send my variable 'backEndResponse' with its value from my Express.js backend to my React.js Frontend. I am not quite sure how to send a variable from the backend to the frontend. I have searched around and can't find any good resources. I would appreciate any help.

Express.js Backend

function getcookie(req) {
    var authCookie = req.headers.cookie;
    if (authCookie = req.headers.cookie) {
        try {
            return authCookie
                .split('; ')
                .find(row => row.startsWith('Auth='))
                .split('=')[1];
        } finally {
            if (authCookie = result) {
                backEndResponse = true
                console.log(backEndResponse);
                console.log(result);
            } else {
                backEndResponse = false
                console.log(backEndResponse);
                console.log(result);
            }

        }
    } else {

    }
}

app.get('/auth', (req, res) => {
    getcookie(req)

    if (backEndResponse) {
        res.json(backEndResponse); // OR json({ message: "Authorised" })
      } else {
        res.json(backEndResponse); // OR json({ message: "Unauthorised" })
    }
});

Frontend React.js

    const useAuth = () => {
    const [data, setData] = useState();

      useEffect(() => {
          const fetchAuthData = () => {
            const result = axios('http://localhost:5000/auth');

            console.log(result)
            setData(result.data);
            
          };

          fetchAuthData()
      }, []);

      
    // Logic to check if backEndResponse is true or false
    if (data) {
        const authorized = {loggedIn: true}
        return authorized && authorized.loggedIn;
    } else {
        const authorized = {loggedIn: false}
        return authorized && authorized.loggedIn;
    }
  }


const ProtectedRoutes = () => {
    const isAuth = useAuth();
    return isAuth ? <Outlet/> : <Navigate to="/login" />;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You won't be able to send a variable directly, rather you will send a payload in a certain shape that best represents the data suited to the applications needs. To send a response payload in an express route use something like the following:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...
  res.json(backEndResponse);
});

If you were intending to provide more information in the response such as HTTP headers differing based on the of backEndResponse then you might consider:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...

  // send HTTP Ok if true, otherwise Bad Request
  // consider handling 400 and/or 500 errors too
  if (backEndResponse) {
    res.status(200).json(true); // OR json({ message: "Authorised" })
  } else {
    res.status(401).json(false); // OR json({ message: "Unauthorised" })
  }
});

A component fetching the above endpoint would be similar to:

const MyComponent = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchAuthData = async () => {
      const result = await axios('http://localhost:5000/auth');

      setData(result.data); // true/false OR { message: "Authorised" }
    };

    fetchAuthData();
  }, []);

  // display payload
  return (<div>{JSON.stringify(data)}</div>)
}

There is an opportunity to refactor the above into a custom hook should you find the need to reuse the functionality across multiple components.

about 4 years ago · Juan Pablo Isaza Report

0

axios request is async function, so you should do like that,

const useAuth = async () => {
  try {
    const res = await axios.get('http://localhost:5000/auth', {
      withCredentials: true
    })
    return true
  } catch (e) {
    return false
  }
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!