<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ passportjs - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ passportjs - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 09 May 2026 14:06:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/passportjs/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Authenticate Your React App with Passport.js ]]>
                </title>
                <description>
                    <![CDATA[ Authentication is a major part of any serious React application. You need to have a good and reliable way to authenticate your users in your developer tool belt. There are dozens of authentication solutions to choose from today, many of which come wi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-passport-authentication/</link>
                <guid isPermaLink="false">66d037d015ea3036a953994e</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ passportjs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Mon, 19 Sep 2022 22:29:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/passport-react.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Authentication is a major part of any serious React application. You need to have a good and reliable way to authenticate your users in your developer tool belt.</p>
<p>There are dozens of authentication solutions to choose from today, many of which come with a price tag. Which one should you choose? </p>
<p>In this tutorial, we're going to take a look at how you can add authentication to your React apps for free using the industry-standard library Passport.js.</p>
<p>By the end, you will understand how Passport works within a real project, plus you will have all the starter code to be able to set up authentication in your future React projects.</p>
<h2 id="heading-why-use-passportjs">Why Use Passport.js?</h2>
<p>Passport.js is a battle-tested library. It has been the go-to solution for authentication in Node.js apps for many years with over 1.7 million weekly downloads. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Screen-Shot-2022-09-19-at-1.00.16-PM.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Passport.js Node Library</em></p>
<p>It allows your users to sign up easily with email and password at no cost. Additionally, Passport also gives us the ability to use different strategies for authentication such as social login through Google or Twitter, among hundreds of other options. </p>
<p>You can view authentication as an essential gateway for your users. You'll need authentication in many cases to not only separate the casual from the serious users of your applications. Authentication is used to provide the necessary experience for different categories of users.</p>
<h2 id="heading-why-not-use-a-dedicated-paid-auth-service">Why Not Use a Dedicated (Paid) Auth Service?</h2>
<p>The need to authenticate your users is a very common problem, but it doesn't mean it's an easy problem to solve. </p>
<p>In fact, this is why so many companies such as Auth0, Clerk.dev, Okta and many others have emerged to provide authentication as a service. In many developers' eyes, getting authentication right comes at a price.</p>
<p>Fortunately for us JavaScript and Node developers, we have a great library in Passport.js, which allows us to wire up authentication in Node environments quite easily.</p>
<p>We are going to take a look at a complete integration of Passport.js within a React application and break down how it works line-by-line.</p>
<h2 id="heading-download-the-project-code">Download the Project Code</h2>
<p>To get the complete code which is available from the official Next.js GitHub, you can <a target="_blank" href="https://github.com/vercel/next.js/tree/canary/examples/with-passport">go to the following repo</a> with NPM or Yarn.</p>
<p>This is going to give you all the project files that we will be looking through, plus it will give you an ideal template to use Passport.js in your next React project. </p>
<p>I would recommend that you download the entire examples folder from <a target="_blank" href="https://github.com/vercel/next.js">https://github.com/vercel/next.js</a> and grab the with-passport folder. The template script included in the README includes broken code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/passport-gif-4.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Passport App Demo</em></p>
<h2 id="heading-how-the-passport-local-strategy-works">How the Passport Local Strategy Works</h2>
<p>To start using Passport in your projects, you'll need to install the main <code>passport</code> library as well as a specific strategy.</p>
<p><strong>Strategies</strong> are different methods with which your users can authenticate themselves. Passport Local is the strategy that Passport provides to enable users to sign up and login in the most traditional way–with email and password.</p>
<p>Both of these are included in the <code>package.json</code> file.</p>
<p>If you look in the lib folder, you can see how <code>passport-local</code> is set up. </p>
<pre><code class="lang-js"><span class="hljs-comment">// /lib/password-local.js</span>

<span class="hljs-keyword">import</span> Local <span class="hljs-keyword">from</span> <span class="hljs-string">'passport-local'</span>
<span class="hljs-keyword">import</span> { findUser, validatePassword } <span class="hljs-keyword">from</span> <span class="hljs-string">'./user'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> localStrategy = <span class="hljs-keyword">new</span> Local.Strategy(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">
  username,
  password,
  done
</span>) </span>{
  findUser({ username })
    .then(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (user &amp;&amp; validatePassword(user, password)) {
        done(<span class="hljs-literal">null</span>, user)
      } <span class="hljs-keyword">else</span> {
        done(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid username and password combination'</span>))
      }
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      done(error)
    })
})
</code></pre>
<p>In the <code>password-local.js</code> file, the strategy is created and takes care of finding a user based off of their username and validating their password. If a user is found it will be returned via the <code>done</code> callback. If not, an error will be thrown. </p>
<p>If you look in <code>/pages/api</code>, you will see all of the server-related code which uses passport. The names of the files correspond to the actions you will need: login logout and sign up.</p>
<h2 id="heading-how-to-sign-up-users-with-passport">How to Sign Up Users with Passport</h2>
<p>If you look at the signup file, it is simply creating a user based off of the data that's provided on the request body and is passed along with the request. </p>
<pre><code class="lang-js"><span class="hljs-comment">// /pages/api/signup.js</span>

<span class="hljs-keyword">import</span> { createUser } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../lib/user'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signup</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> createUser(req.body)
    res.status(<span class="hljs-number">200</span>).send({ <span class="hljs-attr">done</span>: <span class="hljs-literal">true</span> })
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error)
    res.status(<span class="hljs-number">500</span>).end(error.message)
  }
}
</code></pre>
<p>When that's done, the server responds with a 200 success code, meaning your user has been created with the email and password they provided. </p>
<p>If you go back to the lib folder, into user.js, you can see how this <code>createUser</code> function works:</p>
<pre><code class="lang-js"><span class="hljs-comment">// /lib/user.js</span>

<span class="hljs-keyword">const</span> users = []

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">{ username, password }</span>) </span>{
  <span class="hljs-comment">// Here you should create the user and save the salt and hashed password (some dbs may have</span>
  <span class="hljs-comment">// authentication methods that will do it for you so you don't have to worry about it):</span>
  <span class="hljs-keyword">const</span> salt = crypto.randomBytes(<span class="hljs-number">16</span>).toString(<span class="hljs-string">'hex'</span>)
  <span class="hljs-keyword">const</span> hash = crypto
    .pbkdf2Sync(password, salt, <span class="hljs-number">1000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>)
    .toString(<span class="hljs-string">'hex'</span>)
  <span class="hljs-keyword">const</span> user = {
    <span class="hljs-attr">id</span>: uuidv4(),
    <span class="hljs-attr">createdAt</span>: <span class="hljs-built_in">Date</span>.now(),
    username,
    hash,
    salt,
  }

  <span class="hljs-comment">// This is an in memory store for users, there is no data persistence without a proper DB</span>
  users.push(user)

  <span class="hljs-keyword">return</span> { username, <span class="hljs-attr">createdAt</span>: <span class="hljs-built_in">Date</span>.now() }
}
</code></pre>
<p><code>createUser</code> takes a username and password and <strong>hashes</strong> the password so it can be saved securely and not as plain text. Then the created user is added to an array of users. </p>
<p>If and when you connect a database to this project, this is where you would actually create a new user in your database and swap that out with <code>users.push</code></p>
<h2 id="heading-how-to-log-in-users-with-passport">How to Log In Users with Passport</h2>
<p>If you look at how your app works, after signing up and creating your user, the user then has to log in. When a user logs in, they make requests to <code>/api/login</code>. </p>
<p>This is where Passport actually steps in and does authentication for you. In this example, we're using the <code>next-connect</code> library to initialize passport before the POST request is made (upon login form submission). </p>
<pre><code class="lang-js"><span class="hljs-comment">// /api/login.js</span>

passport.use(localStrategy)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> nextConnect()
  .use(passport.initialize())
  .post(<span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> authenticate(<span class="hljs-string">'local'</span>, req, res)
      <span class="hljs-comment">// session is the payload to save in the token, it may contain basic info about the user</span>
      <span class="hljs-keyword">const</span> session = { ...user }

      <span class="hljs-keyword">await</span> setLoginSession(res, session)

      res.status(<span class="hljs-number">200</span>).send({ <span class="hljs-attr">done</span>: <span class="hljs-literal">true</span> })
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(error)
      res.status(<span class="hljs-number">401</span>).send(error.message)
    }
  })
</code></pre>
<p>The login endpoint receives the data from your front end. When the POST request is made with the user's credentials, namely the email and password, it uses this authenticate function from passport to take care of authenticating your request. </p>
<p>Then another function, <code>setLoginSession</code>, takes care of creating a session for the logged-in user with the package <code>@hapi/iron</code>. </p>
<pre><code class="lang-js"><span class="hljs-comment">// /lib/auth.js</span>

<span class="hljs-keyword">import</span> Iron <span class="hljs-keyword">from</span> <span class="hljs-string">'@hapi/iron'</span>
<span class="hljs-keyword">import</span> { MAX_AGE, setTokenCookie, getTokenCookie } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth-cookies'</span>

<span class="hljs-keyword">const</span> TOKEN_SECRET = process.env.TOKEN_SECRET

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setLoginSession</span>(<span class="hljs-params">res, session</span>) </span>{
  <span class="hljs-keyword">const</span> createdAt = <span class="hljs-built_in">Date</span>.now()
  <span class="hljs-comment">// Create a session object with a max age that we can validate later</span>
  <span class="hljs-keyword">const</span> obj = { ...session, createdAt, <span class="hljs-attr">maxAge</span>: MAX_AGE }
  <span class="hljs-keyword">const</span> token = <span class="hljs-keyword">await</span> Iron.seal(obj, TOKEN_SECRET, Iron.defaults)

  setTokenCookie(res, token)
}
</code></pre>
<p>This takes care of creating a cookie for your user which can now be used to identify and therefore authenticate them on future requests until the cookie expires or the user logs out. </p>
<p>If a user goes through the process of logging in they'll be redirected to the homepage. This is due to a special hook called <code>useUser</code> within your login page. </p>
<pre><code class="lang-js"><span class="hljs-comment">// /pages/login.js</span>

<span class="hljs-keyword">const</span> Login = <span class="hljs-function">() =&gt;</span> {
  useUser({ <span class="hljs-attr">redirectTo</span>: <span class="hljs-string">'/'</span>, <span class="hljs-attr">redirectIfFound</span>: <span class="hljs-literal">true</span> })

  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p><code>useUser</code> makes a request to the <code>/api/user</code> endpoint. In this endpoint, it takes care of getting the session from the request that was made and finding a user based off of it and finally returning that user. </p>
<pre><code class="lang-js"><span class="hljs-comment">// /api/user.js</span>

<span class="hljs-keyword">import</span> { getLoginSession } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../lib/auth'</span>
<span class="hljs-keyword">import</span> { findUser } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../lib/user'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">user</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> session = <span class="hljs-keyword">await</span> getLoginSession(req)
    <span class="hljs-keyword">const</span> user = (session &amp;&amp; (<span class="hljs-keyword">await</span> findUser(session))) ?? <span class="hljs-literal">null</span>

    res.status(<span class="hljs-number">200</span>).json({ user })
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error)
    res.status(<span class="hljs-number">500</span>).end(<span class="hljs-string">'Authentication token is invalid, please log in'</span>)
  }
}
</code></pre>
<p>For this request, we use the package <code>swr</code> which allows us to make GET requests using a convenient hook called <code>useSWR</code>. </p>
<p>When the user data is sent back to the <code>useUser</code> hook, it redirects the user to a given route based off of the provided <code>redirectTo</code> property. Since this was set to forward slash, it will redirect your user to the homepage. You can change this property's value to be whatever page you want the user to visit immediately after logging in instead of staying on the login page. </p>
<h2 id="heading-how-to-log-out-users-with-passport">How to Log Out Users with Passport</h2>
<p>Finally, the last action Passport takes care of in this app is logging out the user. Fortunately logging them out is as simple as removing the cookie you created on login.  </p>
<p>You log out your user and remove the cookie on the server side. You do this by making a GET request to <code>/api/logout</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// /api/logout</span>

<span class="hljs-keyword">import</span> { removeTokenCookie } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../lib/auth-cookies'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logout</span>(<span class="hljs-params">req, res</span>) </span>{
  removeTokenCookie(res)
  res.writeHead(<span class="hljs-number">302</span>, { <span class="hljs-attr">Location</span>: <span class="hljs-string">'/'</span> })
  res.end()
}
</code></pre>
<p>In it, you use a function <code>removeTokenCookie</code> to delete the cookie that you created when the session was made. After doing so, the user is redirected back to the homepage using a server-side redirect. </p>
<h2 id="heading-how-to-get-better-at-authenticating-users">How to Get Better at Authenticating Users</h2>
<p>The best way to get a good understanding of Passport and authentication in general is to work with it. As long as you are a developer, it will be an essential component to understand and implement.</p>
<p>Beyond my explanations here, be sure to run this application on your own. Play around with signing up logging in and logging out users so you can get a good understanding of what's actually going on when you authenticate them. </p>
<p>I hope this project serves as a good starting point for any React application you have where you want to feature authentication. If you want to extend this example beyond email and password auth, be sure to check out Passport's website for all 500+ available strategies that your users can use to sign in.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to set up Twitter OAuth using Passport.js and ReactJS ]]>
                </title>
                <description>
                    <![CDATA[ By Leanne Zhang Getting started This is a simple authentication tutorial for building a Twitter Authentication web application using Passport API. It’s a side project that I worked on for education purposes. I broke down this tutorial into two parts.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-twitter-oauth-using-passport-js-and-reactjs-9ffa6f49ef0/</link>
                <guid isPermaLink="false">66c35499df235c0b59e2531c</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ passportjs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 03 May 2019 16:23:29 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*hYMUC_9w-Szc075Uztq2bw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Leanne Zhang</p>
<h3 id="heading-getting-started"><strong>Getting started</strong></h3>
<p>This is a simple authentication tutorial for building a Twitter Authentication web application using <a target="_blank" href="http://www.passportjs.org/packages/passport-twitter/">Passport API</a>. It’s a side project that I worked on for education purposes.</p>
<p>I broke down this tutorial into two parts. The first part focuses on building authentication routes in the backend. The second part focuses on building UI components in the front-end using React.</p>
<h4 id="heading-tech-stack"><strong>Tech Stack</strong></h4>
<ul>
<li>Server Side: <a target="_blank" href="https://nodejs.org/en/">Node.js</a>, <a target="_blank" href="https://expressjs.com/">Express.js</a>, <a target="_blank" href="http://www.passportjs.org/packages/passport-twitter/">Passport Twitter API</a>, <a target="_blank" href="https://www.mongodb.com/">MongoDB</a>,</li>
<li>Client: <a target="_blank" href="https://reactjs.org/">ReactJS</a></li>
</ul>
<h4 id="heading-what-are-we-going-to-build"><strong>What are we going to build?</strong></h4>
<ul>
<li>User clicks on login button which redirects to Twitter OAuth authentication page.</li>
<li>Once the OAuth has been successfully authenticated to Twitter, the user will be redirected back to the web application home page.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/DT6OHJBlHLyZ1cMi9iU5S7-WXsToLAP5o1mn" alt="Image" width="600" height="400" loading="lazy">
<em>Authenticate via passport-twitter</em></p>
<p><a target="_blank" href="http://www.passportjs.org/"><em>Passport.js.</em></a> <em>offers authentication APIs to other OAuth service providers such as Google and Facebook. As an example, I chose to use Twitter as an OAuth service provider.</em></p>
<h4 id="heading-what-is-oauth"><strong>What is OAuth?</strong></h4>
<p>Open Authorization is a standard for granting your web application access to a third-party sign-in service like Twitter, Facebook, or Google, which returns an OAuth token. An OAuth Token is a credential that can be used by an application to access an external service API.</p>
<p>In this project, I'm using <code>passport-twitter</code> middleware to handle Twitter authentication using the OAuth 1.0 API, because it saves time and handles all the complex authentication process behind the scene.</p>
<h4 id="heading-what-are-the-server-endpoints">What are the server endpoints?</h4>
<p><strong>/auth/twitter —</strong> authenticate via passport twitter</p>
<p><strong>/auth/login/success —</strong> returns login success response with user information</p>
<p><strong>/auth/login/failed —</strong> returns login failed message</p>
<p><strong>/auth/logout —</strong> log-out and redirects to client home page</p>
<p><strong>/auth/twitter/redirect —</strong> redirect to home page if login succeeded or redirect to <em>/auth/login/failed</em> if failed</p>
<h4 id="heading-architecture-diagram">Architecture Diagram</h4>
<p>Here is an overview of the architecture diagram which we will be going over in more detail.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/2ZnSn0-X1F2Unvll-wTomYQJl-jPG3cT8jSx" alt="Image" width="600" height="400" loading="lazy">
<em>Architecture Diagram</em></p>
<h4 id="heading-project-structure">Project Structure</h4>
<p>I separated server and client logic in different folders to be clear and clean. My <strong>server</strong> is running on <em>localhost:4000,</em> whereas the <strong>client</strong> is running on <em>localhost:3000</em>. (Feel free to define your own port.)</p>
<pre><code>|-- twitter-auth-project|   |-- server|   |   |-- index.js|   |   |-- package.json|   |-- client|   |   |-- src|   |   |   |-- index.jsx|   |   |   |-- package.json
</code></pre><h3 id="heading-implementation">Implementation</h3>
<h4 id="heading-part-1-register-your-app-as-an-oauth-provider-at-twitter-application-site"><strong>Part 1: Register your app as an OAuth provider at Twitter Application Site</strong></h4>
<p>First things first, register your application at <a target="_blank" href="https://apps.twitter.com/">Twitter Application Management</a>. You will be issued with a consumer key (API Key) and consumer secret (API Secret) that you can use in passport strategy later on.</p>
<p>You will also need to configure a callback URL. This is the callback URL after the OAuth has been authenticated successfully.</p>
<p>For local development purpose, I customized my callback URLs to be the client URL which is <strong>localhost:3000</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/wgnQM7zKUznjvIjAK976b1Mqbm3t2Ipct1RP" alt="Image" width="600" height="400" loading="lazy">
_[https://developer.twitter.com/en/apps/create](https://developer.twitter.com/en/apps/create" rel="noopener" target="<em>blank" title=")</em></p>
<h4 id="heading-part-2-setup-express-server-for-twitter-authentication"><strong>Part 2: Setup Express Server for Twitter Authentication</strong></h4>
<p>I chose <a target="_blank" href="https://expressjs.com/">Express.js</a> to set up the server on the backend. <strong>Express.js</strong> is a web application framework for Node.js which designed to build APIs.</p>
<pre><code>|-- server|   |-- config|   |   |-- keys.js|   |   |-- passport-setup.js|-- |-- models|   |   |-- user-model.js|   |-- routes|   |   |-- auth-routes.js|   |-- index.js|   |-- package.json
</code></pre><p><code>npm install express</code> to install an <a target="_blank" href="https://expressjs.com/en/starter/hello-world.html">express</a> server. The server runs on <em>http://localhost:4000</em>.</p>
<p><code>index.js</code> is the entry point for all the server endpoints.</p>
<p><code>/routes/auth-routes.js</code> contains all the authentication endpoints.</p>
<p><code>/config/keys.js</code> contains all the Twitter API consumer keys, and database configs. <em>You can copy them and put your own keys.</em></p>
<h4 id="heading-part-3-setup-authentication-routes"><strong>Part 3: Setup authentication routes</strong></h4>
<p>Previously in the “What are the server endpoints?” section, we have identified the authentication endpoints to Twitter API.</p>
<blockquote>
<p><strong>/auth/twitter —</strong> authenticate via passport twitter</p>
<p><strong>/auth/login/success —</strong> returns login success response with user information</p>
<p><strong>/auth/login/failed —</strong> returns login failed message</p>
<p><strong>/auth/logout —</strong> logout and redirects to client home page</p>
<p><strong>/auth/twitter/redirect —</strong> redirect to home page if login succeeded or to <em>/auth/login/failed</em> if failed</p>
</blockquote>
<p>Let’s put them into practice.</p>
<p><code>/routes/auth-routes.js</code></p>
<p>In <code>index.js</code>, import <code>routes/auth-routes</code>,</p>
<p><code>npm install cors</code> — support cross-origin browser</p>
<h4 id="heading-part-4-setup-twitter-strategy-using-passport-api"><strong>Part 4: Setup Twitter strategy using Passport API</strong></h4>
<p><a target="_blank" href="http://www.passportjs.org/docs/"><strong>Passport API</strong></a> is a middleware we use to authenticate via Twitter OAuth. Passport API does the login authentication behind the scene so you do not need to handle the complex logic. It has also different authentication strategies (i.e GoogleStrategy, FacebookStrategy). In my example, I chose to use <a target="_blank" href="http://www.passportjs.org/docs/twitter/">TwitterStrategy</a> to login via a Twitter account.</p>
<h4 id="heading-part-5-setup-and-connect-a-database"><strong>Part 5: Setup and connect a database</strong></h4>
<p>When the system successfully authenticates the user through PassportAPI, it will need to store the user in a database so it can retrieve this user information to the client.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/olggPPJCKJy8Y39CLOIoZcJv5EcPiAa2qLPN" alt="Image" width="600" height="400" loading="lazy">
<em>architecture diagram</em></p>
<p>I’m using MongoDB to store the user login information.</p>
<p>Part 5.1 — Sign up mlab and follow the instructions here: <a target="_blank" href="https://mlab.com/"><strong>https://mlab.com/</strong></a></p>
<p>Part 5.2 — Add MongoDB credentials in <code>keys.js</code></p>
<p>Part 5.3 — Establish a MongoDB connection using mongoose</p>
<p><code>npm install mongoose</code> to connect to MongoDB.</p>
<blockquote>
<p><em>“Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, and query building.</em>” (<a target="_blank" href="https://mongoosejs.com/">https://mongoosejs.com/</a>)</p>
</blockquote>
<p>Part 5.4 — Create a user object model that represents the user profile in the database record</p>
<p><code>/models/user-model.js</code></p>
<h4 id="heading-part-6-save-and-fetch-user-from-a-database"><strong>Part 6: Save and fetch user from a database</strong></h4>
<p>Once the Passport API successfully authenticated via Twitter OAuth, our server saves the user information to the MongoDB. If this user already exists, the system simply finds the current user from the database and returns the user to the client. This is all done using mongoose APIs.</p>
<p><code>/config/passport-setup.js</code></p>
<h4 id="heading-part-7-use-client-session-to-store-cookie-session"><strong>Part 7: Use client session to store cookie session</strong></h4>
<p>Every time the user logins a website, the browser remembers this user information so that the user does not need to log in again. How this user gets remembered is through an HTTP cookie. An HTTP cookie contains encrypted data about the user and how long the session lasts.</p>
<p>If you login to any webpage, and open the DevTools, you can see the cookies have been set in the browser.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/u1oOba61pi1OvWgDmeQMWUOobbNl7JsG4w2r" alt="Image" width="600" height="400" loading="lazy">
<em>After a successful login, cookies are set in the browser. Open DevTools, go to Application | Cookies.</em></p>
<p>Serialization and deserialization are important concepts to know. <strong>Serialization</strong> is when the user gets encrypted from the database and sends it back to the browser as a cookie. <strong>Deserialization</strong> is when the user cookie gets decrypted from the browser to the database.</p>
<p>In order to support login sessions, Passport will serialize and deserialize user instance to and from the session.</p>
<p><code>/config/passport-setup.js</code></p>
<p>Here is the final <code>index.js</code> using cookie-session.</p>
<p>I chose to use <code>cookie-session</code> as a middle to store session data on the client.</p>
<pre><code>$ npm install cookie-session
</code></pre><p>Also, use cookieSession in <code>index.js</code></p>
<pre><code>app.use(cookieSession({  <span class="hljs-attr">name</span>: <span class="hljs-string">'session'</span>,  <span class="hljs-attr">keys</span>: [<span class="hljs-comment">/* secret keys */</span>],  <span class="hljs-attr">maxAge</span>: <span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span> <span class="hljs-comment">// session will expire after 24 hours}))</span>
</code></pre><p><code>passport.session()</code> acts as a middleware to alter the req object and change the encrypted user value that is currently the session sig (from the client cookie) into a user object.</p>
<p><em>Optional step</em>:</p>
<p>I customized the localhost:4000/ root URL to show success message if login correctly otherwise shows a failed message.</p>
<h3 id="heading-next-step-client-setup-login-page-and-logout-page-using-react"><strong>Next Step: Client — Setup Login Page and Logout Page using React</strong></h3>
<p>I built the front end components using <a target="_blank" href="https://reactjs.org/">React</a>, and <a target="_blank" href="https://github.com/ReactTraining/react-router">React Router</a> to set up links.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yrUyRcfvEDo8aYJSDidulrhgCzUV1p90EVyH" alt="Image" width="600" height="400" loading="lazy">
<em>Login Page and Logout Page</em></p>
<h4 id="heading-functionality"><strong>Functionality</strong></h4>
<p>The page contains a header with home and login/logout button. Initially, the page will display the “welcome” message and “login” button. Once the user has authenticated via twitter authentication, it will display the username and “logout” button.</p>
<h4 id="heading-client-setup">Client setup</h4>
<pre><code>client|-- src|   |-- components|   |   |-- Header.jsx|   |   |-- Homepage.jsx|   |-- App.js|   |-- AppRouter.js|   |-- index.js|   |-- index.css|   |-- serviceWorker.js|-- package.json
</code></pre><h4 id="heading-identify-ui-components">Identify UI components</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/UHGcoXjPC61QZx7nWr7aPR13FHhDDGLNr7Lv" alt="Image" width="600" height="400" loading="lazy">
<em>UI components</em></p>
<ul>
<li>HomePage: a container that displays welcome and user information. Calls <em>/auth/login/success</em> endpoint. If the endpoint succeeded, the user information will be stored in the <em>user</em> object and the state of <em>authenticated</em> will be set <em>true</em>. The page shows a message that <em>“You have login successfully”</em>. If the endpoint failed, the user is not authenticated, and the <em>page displays “Welcome”.</em></li>
<li>Header: It handles navigation. When the user is authenticated, “login” will be changed to “logout”. The <em>authenticated</em> state is passed down from HomePage as a prop.</li>
</ul>
<h4 id="heading-implementation-1">Implementation</h4>
<p>HomePage.jsx: a container that displays welcome and user information</p>
<p>Header.jsx — navigation component</p>
<p>Lastly, set up Route that navigates to HomePage in the AppRouter.jsx and App.jsx</p>
<p>Thank you so much for reading this blog post. I hope you found it helpful.</p>
<p>The entire project is available on my Github: <a target="_blank" href="https://github.com/leannezhang/twitter-authentication">https://github.com/leannezhang/twitter-authentication</a></p>
<p>If you have any comments or feedback, please feel free to comment below or reach me.</p>
<p>Twitter: @ liyangz</p>
<h4 id="heading-reading-materials">Reading Materials</h4>
<ul>
<li><a target="_blank" href="https://github.com/passport/express-4.x-twitter-example">Passport Twitter Example</a></li>
<li><a target="_blank" href="https://github.com/jaredhanson/passport-twitter">Passport Twitter</a></li>
<li><a target="_blank" href="https://youtu.be/sakQbeRjgwg">Passport Google API Tutorial</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
