0

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

Ziad
  • 3
  • 3
  • This thread should help you. You need to pass the parameters as query strings to the redirect. https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context – Joel Hager Feb 10 '23 at 02:20

2 Answers2

0

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.
Nico
  • 423
  • 1
  • 8
0

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
  }

}    
marijak
  • 1
  • 2