Salman Kazi
Salman Kazi

Reputation: 41

How to Redirect From Backend To FrontEnd after Authentication

I Have My Backend (nodejs) running on another Port And My Frontend (React) Running On Another Port...So After After Sending Credentials To Backend And Authentication...How Can I Redirect To Front End ?

Upvotes: 3

Views: 12219

Answers (5)

godofjs
godofjs

Reputation: 113

in my case, I was handling the verifyEmail on the backend of a nest.js server.

How I was able to redirect to the frontend after handling the request, was to use the res.redirect from express.


  @Get('verify/:token')
  async verifyUser(@Param('token') token, @Res() response: Response): Promise<any> {
    const redirectUrl = await  this.authService.verifyUserEmail(token);
    response.redirect(redirectUrl);
    return {redirectUrl};
  }

And, it worked like a charm.

Upvotes: 1

Modi Mohammed
Modi Mohammed

Reputation: 179

From the frontend, on click of login button, you can create a function called login() something like below and redirect based on the response received from the backend

App.tsx

login() {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'test', password: 'password' })
    };
    fetch('http://localhost:5000', requestOptions)
        .then(response => response.json())
        .then(data => history.push('/someRoute'))
        .catch(err => history.push('/login'));
}

Upvotes: 1

millenion
millenion

Reputation: 1907

In your case, you'd better auth request through Ajax, that way you can return some kind of jwt token if you're using it, or trigger any other session related action on frontend on successful login.

Upvotes: 1

Hidayat Arghandabi
Hidayat Arghandabi

Reputation: 194

You may use a web API (Express JS) in nodejs to build web api and frontend any plainJS or modren libaries that will send HTTP request to backend. It will help more.

Upvotes: 1

sromeu
sromeu

Reputation: 304

res.writeHead(302, {
    Location: 'http://front-end.com:8888/some/path'
});
res.end();

If you specify the full url you can redirect to another port using NodeJS.

Upvotes: 1

Related Questions