Ziad
Ziad

Reputation: 3

Sending data from backend to React frontend via express - no ejs

I currently have 2 directories in my project, one for backend using express/axios and one for my React frontend. I have a discord authentication page which correctly authenticates and saves a user to my SQL database and express automatically redirects and sends the user information to an html page.

The problem is when I go to redirect the user after authenticating. I want to redirect them back to my React web application and also send the user information to the frontend. I cannot figure out how to do this without using ejs and other third-party applications.

This is my backend code and I want to use res.send(), res.redirect() etc... to be able to give the route which my react page is currently running (localhost:3000) the required data.

    const { code } = req.query;
    if (code) {
        try {
            const { data: credentials } = await exchangeAccessCodeForCredentials({
                client_id: ID,
                client_secret: SECRET,
                grant_type: "authorization_code",
                code: code.toString(),
                redirect_uri: REDIRECT_URL,
            });
            const { data: user } = await getDiscordUserDetails(credentials.access_token);
            const newUser = await createUser(buildUser(user, credentials));
            res.setHeader("Auth", newUser.discordId);
            res.redirect("http://localhost:3000");
        } catch (err) {
            console.log(err);
            res.sendStatus(400);
        }
    }
}

I've also tried to retrieve that data from the headers, but the custom headers I set never show up when I log them...

async function trying() {
    var req = new XMLHttpRequest();
    req.open("GET", document.location, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    alert(headers);
}

Please let me know if there is a way to easily send data to the frontend using only express and React. Thank you

Upvotes: 0

Views: 561

Answers (2)

marijak
marijak

Reputation: 1

You can send data from backend as json:

const your_function = (req, res) => { 
 try {
  // ...
  res.json({ auth: newUser.discordId, redirect: "http://localhost:3000" })
 } catch (error) {
  res.json({error: error.message})
 }

So you can access it in frontend through fetch/axios, for example:

const getYourData = async () => {
  const response = await fetch(yourUrl, {
   // options, if applicable
  });
  const json = await response.json();

  if(!response.ok){
   console.log(json.error)
  }
  
  if(response.ok){
   localStorage.setItem('user', JSON.stringify(json.auth)); // or whatever you want to do with newUser.discordId
   window.location.href = json.redirect
  }

}    

Upvotes: 0

Nico
Nico

Reputation: 421

What you need to do, is send all the information of the user to your react application, and handle of the redirection there.

So you have two scenarios:

  1. The authentication is succesful, so you return the user information from your backend, and your React app should redirect to the other page.
  2. The authentication failed, so your return an error or a 403 status code, and your React app should show the error there.

Upvotes: 0

Related Questions