Search code examples
node.jsreactjspassport-local

ReactJs frontend & Passport NodeJs backend


I am building a project which is API RESTful with NodeJS, Express & Passport. And for the Frontend of this application I want to use ReactJS.

Can I create a separate project with create-app-react for my frontend and fetch my API while keeping the benefits of Passport ? Or I should send always the user's information in my request? Or serve my Frontend on the same server of the API?


Solution

  • Yes, you can have a client & a server on 2 differents port, and keep the benefits of Passport.

    But for that, when you fetch you API use credentials : 'include'

    Because, by default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

    Example:

    fetch('https://example.com', {
      credentials: 'include'  
    })
    .then( res => {
      // Some stuff...
    })
    .catch(err => {
      console.log(err);
    });