So I'm working on a project that incorporates React, Express.js+Passport and Webpack. I understand the concept of pushing everything to a 'master' React component via react-router, then letting it hash out what gets displayed for the given route. That would work great here, I think. To be upfront, I am new to React.
My concerns are:
1) Can I/how can I still use Passport to authenticate my routes? If I understand react-router correctly, I'll have one route in my express app.js file, pointing to, say, a React component named <Application/>
. However, Passport needs router.get('/myroute', isAuthenticated, callback)
to check the session. Is it still possible to do so with react-router?
2) Furthermore, if this is possible, how do I pass values from the route in Express into my views, in React? I know in a typical view, I could use <%= user %>
or {{user}}
if I passed that from my route. Is that possible here?
Passport is Authentication Middleware for Node. JS, it is not for any specific method of authentication, the method for authentication like OAuth, JWT is implemented in Passport by Strategy pattern, so it means that you can swap the authentication mechanism without affecting other parts of your application.
In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.
Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.
Split a view rendering path from API paths. After all you can set the authentication logic into api calls.
//Auth check middleware function isAuth(req, res, next) {...} //API routes app.post("api/users/login", function() {...}); app.post("api/users/logout", function() {...}); app.get("api/purchases", isAuth, function() {...}); //and so on... //Wild card view render route app.use(function(req, res) { var router = Router.create({ onAbort: function(options) {...}, onError: function(error) {...}, routes: //your react routes location: req.url }); router.run(function(Handler) { res.set("Content-Type", "text/html"); res.send(React.renderToString(<Handler/>)); }); });
So you have to solve how you're going to pass server side rendered data in views to a client side (choose your isomorphic data transferring technique).
You can also create views and the redirection logic on a client side only and firstly render react components in an "awaiting" state that will be resolved on a client after a component will be mounted (check auth state via an API call).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With