MDalt MDalt - 1 month ago 11
Node.js Question

Providing a React Router component with state variables after being redirected from the server (using Redux for state-handling)

I am building a client application using React and Redux, with server-side API endpoints set-up using Node.

For one feature I would like to send out a token in an email, then upon clicking a link (something like

website.com/token?email=dave.example@something.com&token=3ad56gyhg
) verify their token/email using a server-side API, before redirecting them to a particular page in React (using React Router).

I anticipate the Node API would look something like this:

app.get('/token', (req, res, next) => {
//code here.....
//goes and checks the email and token code match what is in the database
if (success) {
res.redirect('/welcome');
}
}


Once I've redirected to the appropriate React router endpoint, how do I provide state/props relevant to the user to any components? For example, I might want to use their email address on a page once their token has been verified.

ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory}>
<Route component={App}>
<Route path="/" component={EntryPoint} />
<Route path="/welcome" component={WelcomeContainer} />
</Route>
</Router>
</Provider>,
document.getElementById('root')
);


Would I have to go down the isomorphic route and create a store on the server? Would the component need to go back and get an 'initial state' from the server?

Answer

You have a static HTML/CSS/JS server and you have a Node API. In this case, you can't 'template' the HTML that you send to the client. That means that you can only pass data to your react application via URL params.

app.get('/token', (req, res, next) => {
    //code here.....
    //goes and checks the email and token code match what is in the database
    if (success) {
         res.redirect(`/welcome/${encodeURIComponent(email)}`);
    }
}

Then when your component loads, check for the query param:

ReactDOM.render(
<Provider store={store}>
    <Router history={hashHistory}>
        <Route component={App}>
            <Route path="/" component={EntryPoint} />
            <Route path="/welcome/:email" component={WelcomeContainer} />
        </Route>
    </Router>
</Provider>,
document.getElementById('root')
);

Alternative:

  • /token redirects to your webapp.
  • Your react application now picks up the email & token params and then makes an API request to /verify/token with the email & token parameters.
  • Your application handles the API request (which returns a success/fail) and then redirects internally to /welcome.

This is the way I've usually done this. The key is to make sure that when the user clicks on the verify link, they are taken directly to the webapp. The webapp does the API verification business.