How can I use passportjs and reactjs together? How can I use passportjs and reactjs together? reactjs reactjs

How can I use passportjs and reactjs together?


  • Use componentDidMount/useEffect to get authentication status. Set status in react state.
  • If not authenticated, Show the link to Login/Signup page or redirect.
  • If authenticated, you can return additional protected data or show the link to the protected page.(When showing private data, check authentication status on every page by using componentDidMount/useEffect)

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 + jsonwebtokenfrontend :-> react/ any other framework + redux it works really awesome.


you need to create a middleware function where put the code

function ensureAuthenticated(req, res, next){  if(req.isAuthenticated()) {     return next()   } else {    res.redirect('/')  }}

and then use in a router

app.get('/account', ensureAuthenticated, function(req, res){  // here return some data})

From React probably you have to do a fetch request

fetch('https://your_url/account', {  credentials: 'include'  })

Something like this, you have to make ajax request to the server or by using socket.io or websockets