I have 3 views, (Home, signup, login)made in reactJs, I want to use passport in my project but I dont know how to do it, I have passport configurated and it url is working.
What can I do to manage the session and the user data like we do in ejs or jade?
Yes, definitely, and in fact, Nodejs is the most convenient platform for hosting as well as running a web server for a React application. It's because of two main reasons: Using an NPM (Node Package Manager), Node works alongside the NPM registry to easily install any package through the NPM CLI.
Neither react nor node use any network ports as they have no networking capabilities themselfs. It's the web server (e.g. express js) which uses node as the runtime environment or the database server that use ports. You can serve your assets (react app, html, css) from the same web server.
You can Use passport. js with node. js and also can use jsonwebtoken ,i personally use that very usefull simple to code and pretty secure and easily can use to frontend with react or any other frontend framework .
Client-side example
import React, { useEffect, useState } from 'react'; import { Link } from "react-router-dom"; import axios from 'axios'; function Home() { const [loggedIn, setLoggedIn] = useState(false); useEffect(() => { axios.get('/checkAuthentication') .then(res => { setLoggedIn(res.data.authenticated); }) .catch((error) => { setLoggedIn(false) }); }, []); return ( <div> {loggedIn ? ( <p>Login success</p> ) : ( <div> <Link to="/signup"> Signup </Link> <Link to="/login"> Login </Link> </div> )} </div> ); } export default Home;
Server-side example (req.user must be populated if you set up passport)
app.get("/checkAuthentication", (req, res) => { const authenticated: boolean = typeof req.user !== 'undefined' res.status(200).json({ authenticated, }); });
You can Use passport.js with node.js and also can use jsonwebtoken ,i personally use that very usefull simple to code and pretty secure and easily can use to frontend with react or any other frontend framework . The best thing is backend :-> node.js + passport.js + jsonwebtoken frontend :-> react/ any other framework + redux it works really awesome.
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