{"componentChunkName":"component---src-templates-blog-list-template-js","path":"/engineering/19","result":{"data":{"allMarkdownRemark":{"edges":[{"node":{"excerpt":"It is fine when you and the rest of your team are working on different files. But sometimes, multiple people simultaneously work on the same…","fields":{"slug":"/engineering/git-pull-force/"},"html":"<p>It is fine when you and the rest of your team are working on different files. But sometimes, multiple people simultaneously work on the same files, and that's where the problems arise.</p>\n<p>Just a Note: <code>git pull = git fetch + git merge</code></p>\n<p>In this scenario, when you have local changes in your system and you pull the latest contribution, you got this error.</p>\n<p><code>error: your local changes to the following files would be overwritten by merge: readme.md</code>\n<code>please commit your changes or stash them before you merge.</code>\n<code>Aborting...</code></p>\n<h2 id=\"now-you-have-2-major-choices\" style=\"position:relative;\"><a href=\"#now-you-have-2-major-choices\" aria-label=\"now you have 2 major choices permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Now you have 2 major choices</h2>\n<h3 id=\"choice-1-you-want-to-keep-local-changes\" style=\"position:relative;\"><a href=\"#choice-1-you-want-to-keep-local-changes\" aria-label=\"choice 1 you want to keep local changes permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Choice 1: you want to keep local changes</h3>\n<p><code>git stash</code>  (stash the local changes clean the workspace)\n<code>git pull</code> (pull the latest changes from remote )\n<code>git stash apply</code> (apply the latest stash)</p>\n<p>-----------(or)---------------</p>\n<p><code>git fetch</code> (fetch the local machine folder)\n<code>git stash</code> (stash the local changes clean the workspace)\n<code>git merge '@{u}'</code> (merge the changes from local folder to workspace folder)\n<code>git stash pop</code> (apply the latest stash )</p>\n<p>By default, the stash changes will become staged. If you want to unstage them, use <code>git restore --staged</code> (git ver > 2.25.0).</p>\n<h3 id=\"choice-2-you-do-not-want-the-local-changes\" style=\"position:relative;\"><a href=\"#choice-2-you-do-not-want-the-local-changes\" aria-label=\"choice 2 you do not want the local changes permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Choice 2: you do not want the local changes</h3>\n<p><code>git reset --hard HEAD</code> (reset to the head means remove all local changes)\n<code>git pull</code> (get the latest changes)</p>\n<p>-----------(or)---------------</p>\n<p><code>git fetch</code> (fetch the local machine folder)\n<code>git reset --hard HEAD</code> (reset to the head means remove all local changes)\n<code>git merge '@{u}'</code>  (merge the changes from the local folder to workspace folder)</p>\n<h2 id=\"git-pull---force\" style=\"position:relative;\"><a href=\"#git-pull---force\" aria-label=\"git pull   force permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>git pull --force</h2>\n<p>Now you must be thinking, what is <code>git pull --force</code> then?</p>\n<p>it feels like it would help to overwrite local changes. instead, it fetches forcefully but does not merge forcefully (<code>git pull --force</code> = <code>git fetch --force</code> + <code>git merge</code>).</p>\n<p>Like git push, git fetch allows us to specify which local and remote branch we want to work on. <code>git fetch origin/ft-1:my-ft</code> means the changes in the <code>ft-1</code> branch from the remote repository will end up visible on the local branch <code>my-ft</code>. When such kind of operation modifies the existing history, it is not allowed by the Git without an explicit --force parameter.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n</style>","frontmatter":{"date":"December 03, 2020","updated_date":null,"description":"How to Overwrite Local Changes With Git Force Pull","title":"How to Perform a Git Force Pull","tags":["git"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/b9cea373b830a55754969545351066e3/58556/pull.webp","srcSet":"/static/b9cea373b830a55754969545351066e3/61e93/pull.webp 200w,\n/static/b9cea373b830a55754969545351066e3/1f5c5/pull.webp 400w,\n/static/b9cea373b830a55754969545351066e3/58556/pull.webp 800w,\n/static/b9cea373b830a55754969545351066e3/99238/pull.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Abhimanyu Singh Rathore","github":"abhir9","avatar":null}}}},{"node":{"excerpt":"Introduction In this blog, I will show you how to create a NodeJS server using core http module.  We will create a simple server that will…","fields":{"slug":"/engineering/node-http-module-server/"},"html":"<h3 id=\"introduction\" style=\"position:relative;\"><a href=\"#introduction\" aria-label=\"introduction permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Introduction</h3>\n<p>In this blog, I will show you how to create a NodeJS server using <a href=\"https://nodejs.org/api/http.html\">core http</a> module.  We will create a simple server that will serve static assets and a simple API to return some JSON data. </p>\n<p>In the process, you will also learn about the request and response objects provided by NodeJS, which are used by every other framework built on top of NodeJS like ExpressJS etc. </p>\n<h3 id=\"prerequisites\" style=\"position:relative;\"><a href=\"#prerequisites\" aria-label=\"prerequisites permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Prerequisites</h3>\n<ol>\n<li>NodeJS installed on your system. Download from <a href=\"https://nodejs.org/en/download/\">Here</a></li>\n<li>A basic understanding of JavaScript</li>\n</ol>\n<p>With that in mind, let's begin.</p>\n<h3 id=\"step-1-initialize-the-project\" style=\"position:relative;\"><a href=\"#step-1-initialize-the-project\" aria-label=\"step 1 initialize the project permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 1: Initialize the project</h3>\n<ul>\n<li>\n<p>Create a folder by any name and initialize a node project in it using <code>npm init -y</code></p>\n<ul>\n<li>By this time, you will have a <code>package.json</code> file in your directory.</li>\n</ul>\n</li>\n<li>Create a file called <code>server.js</code> in your directory.</li>\n</ul>\n<h3 id=\"step-2-add-some-static-content\" style=\"position:relative;\"><a href=\"#step-2-add-some-static-content\" aria-label=\"step 2 add some static content permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 2: Add some static content</h3>\n<ul>\n<li>Create a directory called <code>public</code> at the root of your project.</li>\n<li>\n<p>Add a file named <code>index.html</code> with the following content\n<code>index.html</code></p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"html\" data-index=\"0\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\">&lt;!</span><span class=\"mtk12\">DOCTYPE</span><span class=\"mtk1\"> </span><span class=\"mtk12\">html</span><span class=\"mtk1\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">html</span><span class=\"mtk1\"> </span><span class=\"mtk12\">lang</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;en&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">head</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">meta</span><span class=\"mtk1\"> </span><span class=\"mtk12\">charset</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;UTF-8&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">meta</span><span class=\"mtk1\"> </span><span class=\"mtk12\">name</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;viewport&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">content</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;width=device-width, initial-scale=1.0&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">title</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Demo</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">title</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">head</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">body</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">h1</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Coming from the Root </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">h1</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">body</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">html</span><span class=\"mtk17\">&gt;</span></span></code></pre>\n<h3 id=\"step-3-add-our-server-code-to-serve-the-static-assets\" style=\"position:relative;\"><a href=\"#step-3-add-our-server-code-to-serve-the-static-assets\" aria-label=\"step 3 add our server code to serve the static assets permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 3: Add our server code to serve the static assets</h3>\n</li>\n</ul>\n<p>Now we will create a node server that will serve our <code>index.html</code> file when a request is sent to <code>/</code>.</p>\n<p><code>server.js</code></p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"1\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">http</span><span class=\"mtk1\"> = </span><span class=\"mtk11\">require</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;http&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">path</span><span class=\"mtk1\"> = </span><span class=\"mtk11\">require</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;path&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">fs</span><span class=\"mtk1\"> = </span><span class=\"mtk11\">require</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;fs&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">PORT</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">3000</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">hostname</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&#39;localhost&#39;</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// createServer is the http method used to create a web server that takes a callback.</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">server</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">http</span><span class=\"mtk1\">.</span><span class=\"mtk11\">createServer</span><span class=\"mtk1\">(</span><span class=\"mtk12\">serverHandler</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// callback function definition</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">function</span><span class=\"mtk1\"> </span><span class=\"mtk11\">serverHandler</span><span class=\"mtk1\">(</span><span class=\"mtk12\">req</span><span class=\"mtk1\">, </span><span class=\"mtk12\">res</span><span class=\"mtk1\">) =&gt; {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk15\">if</span><span class=\"mtk1\">(</span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">method</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&#39;GET&#39;</span><span class=\"mtk1\"> && </span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">url</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&#39;/&#39;</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk4\">let</span><span class=\"mtk1\"> </span><span class=\"mtk12\">filePath</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">path</span><span class=\"mtk1\">.</span><span class=\"mtk11\">resolve</span><span class=\"mtk1\">(</span><span class=\"mtk12\">__dirname</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;public/index.html&#39;</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk4\">let</span><span class=\"mtk1\"> </span><span class=\"mtk12\">fileExists</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">fs</span><span class=\"mtk1\">.</span><span class=\"mtk11\">existsSync</span><span class=\"mtk1\">(</span><span class=\"mtk12\">filePath</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (!</span><span class=\"mtk12\">fileExists</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk12\">statusCode</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">404</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;text/html&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">end</span><span class=\"mtk1\">(</span><span class=\"mtk8\">`</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">          &lt;html&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">            &lt;body&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">              &lt;h3&gt;Page not found&lt;/h3&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">            &lt;/body&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">          &lt;/html&gt;`</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      } </span><span class=\"mtk15\">else</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk12\">statusCode</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">200</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;text/html&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">fs</span><span class=\"mtk1\">.</span><span class=\"mtk11\">createReadStream</span><span class=\"mtk1\">(</span><span class=\"mtk12\">filePath</span><span class=\"mtk1\">).</span><span class=\"mtk11\">pipe</span><span class=\"mtk1\">(</span><span class=\"mtk12\">res</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk12\">server</span><span class=\"mtk1\">.</span><span class=\"mtk11\">listen</span><span class=\"mtk1\">(</span><span class=\"mtk12\">PORT</span><span class=\"mtk1\">, </span><span class=\"mtk12\">hostname</span><span class=\"mtk1\">, () </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk10\">console</span><span class=\"mtk1\">.</span><span class=\"mtk11\">log</span><span class=\"mtk1\">(</span><span class=\"mtk8\">`Server running at </span><span class=\"mtk4\">${</span><span class=\"mtk12\">hostname</span><span class=\"mtk4\">}</span><span class=\"mtk8\">:</span><span class=\"mtk4\">${</span><span class=\"mtk12\">PORT</span><span class=\"mtk4\">}</span><span class=\"mtk8\">`</span><span class=\"mtk1\">);   </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  })</span></span></code></pre>\n<p>Let's understand what just happened in the above code snippet:</p>\n<ul>\n<li>First of all, we just created a server using the <code>createServer</code> method provided by node <code>http</code> module. <code>createServer</code> takes a callback which will be called when there is an incoming request with <code>req</code> and <code>res</code> parameters.</li>\n<li>In our callback function <code>serverHandler</code>, we have used an <code>if</code> block to check if the incoming request is a <code>GET</code> request and the request <code>url</code> is <code>/</code> then code inside if statement will be executed.</li>\n<li>Then, we check if the <code>index.html</code> which we want to serve exists or not in our public directory using <code>existsSync</code>, which synchronously checks for the file at the given path and returns true if the file exists.</li>\n<li>Then if the file does not exist, we return a 404 status with an HTML response with a Content-Type header to let the browser know that it's an HTML type response.</li>\n<li>If the file exists, we create a readable stream from it using <code>createReadStream</code> method from <code>fs</code> module and pipe it into <code>res</code> object which sends it to the browser.</li>\n<li>Finally, we use <code>server.listen</code> to start our server on the PORT 3000.</li>\n</ul>\n<p>Now it's time to test our server. Run <code>node server.js</code> at the root of the project, and you will see the server running on PORT 3000.\nOpen your browser and enter <code>localhost:3000</code> in the address bar, and you will get the HTML response. </p>\n<h3 id=\"step-4-add-a-basic-api-to-return-some-json-data\" style=\"position:relative;\"><a href=\"#step-4-add-a-basic-api-to-return-some-json-data\" aria-label=\"step 4 add a basic api to return some json data permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 4: Add a basic API to return some JSON data</h3>\n<p>Now we will expand our callback, which we passed to <code>createServer</code> to handle one more <code>GET</code> request at <code>/notes</code>, which will return an array of notes to the browser.</p>\n<p>Update the <code>serverHandler</code> function with the following code snippet in your <code>server.js</code> file</p>\n<p><code>server.js</code></p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"2\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\">  ...</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">function</span><span class=\"mtk1\"> </span><span class=\"mtk11\">serverHandler</span><span class=\"mtk1\">(</span><span class=\"mtk12\">req</span><span class=\"mtk1\">, </span><span class=\"mtk12\">res</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk15\">if</span><span class=\"mtk1\">(</span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">method</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&#39;GET&#39;</span><span class=\"mtk1\"> && </span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">url</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&#39;/&#39;</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk4\">let</span><span class=\"mtk1\"> </span><span class=\"mtk12\">filePath</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">path</span><span class=\"mtk1\">.</span><span class=\"mtk11\">resolve</span><span class=\"mtk1\">(</span><span class=\"mtk12\">__dirname</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;public/index.html&#39;</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk4\">let</span><span class=\"mtk1\"> </span><span class=\"mtk12\">fileExists</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">fs</span><span class=\"mtk1\">.</span><span class=\"mtk11\">existsSync</span><span class=\"mtk1\">(</span><span class=\"mtk12\">filePath</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (!</span><span class=\"mtk12\">fileExists</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk12\">statusCode</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">404</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;text/html&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">end</span><span class=\"mtk1\">(</span><span class=\"mtk8\">`</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">            &lt;html&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">              &lt;body&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">                &lt;h3&gt;Page not found&lt;/h3&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">              &lt;/body&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk8\">            &lt;/html&gt;`</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        } </span><span class=\"mtk15\">else</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk12\">statusCode</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">200</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;text/html&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk12\">fs</span><span class=\"mtk1\">.</span><span class=\"mtk11\">createReadStream</span><span class=\"mtk1\">(</span><span class=\"mtk12\">filePath</span><span class=\"mtk1\">).</span><span class=\"mtk11\">pipe</span><span class=\"mtk1\">(</span><span class=\"mtk12\">res</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk3\">// Newly added code </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">method</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&#39;GET&#39;</span><span class=\"mtk1\"> && </span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">url</span><span class=\"mtk1\"> === </span><span class=\"mtk8\">&quot;/notes&quot;</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk12\">notes</span><span class=\"mtk1\"> = [</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk12\">id:</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk12\">title:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;Demo Note&quot;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          },</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk12\">id:</span><span class=\"mtk1\"> </span><span class=\"mtk7\">2</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk12\">title:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;Another Note&quot;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        ]</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk12\">statusCode</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">200</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;application/json&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">end</span><span class=\"mtk1\">(</span><span class=\"mtk10\">JSON</span><span class=\"mtk1\">.</span><span class=\"mtk11\">stringify</span><span class=\"mtk1\">(</span><span class=\"mtk12\">notes</span><span class=\"mtk1\">));</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      } </span><span class=\"mtk15\">else</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">setHeader</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;Content-Type&#39;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&#39;application/json&#39;</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk12\">res</span><span class=\"mtk1\">.</span><span class=\"mtk11\">end</span><span class=\"mtk1\">(</span><span class=\"mtk10\">JSON</span><span class=\"mtk1\">.</span><span class=\"mtk11\">stringify</span><span class=\"mtk1\">({</span><span class=\"mtk12\">message:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">`</span><span class=\"mtk4\">${</span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">method</span><span class=\"mtk4\">}</span><span class=\"mtk8\"> is not supported for </span><span class=\"mtk4\">${</span><span class=\"mtk12\">req</span><span class=\"mtk1\">.</span><span class=\"mtk12\">url</span><span class=\"mtk4\">}</span><span class=\"mtk8\">`</span><span class=\"mtk1\">}))</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      } </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  ...</span></span></code></pre>\n<ul>\n<li>Here, we have added one more <code>if</code> statement to handle the request coming at <code>/notes</code> .</li>\n<li>We return a notes array in the JSON format, and we are setting the Content-Type header to be of <code>application/json</code> for the browser to process it accordingly.</li>\n<li>We have also added an else statement to handle all other requests where we simply return a message to the browser that the request is not supported.</li>\n</ul>\n<p>With that, we have created a simple node server to serve static content as well a simple API to return JSON data. </p>\n<h3 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Conclusion</h3>\n<p>We saw how we had to handle each request with its method and the URL. With an increasing number of routes, such things become hard to manage as we will have to add multiple if statements. And that's why frameworks like ExpressJS, HapiJS exist, which makes creating servers in NodeJS very easy. But it's important to know what happens under the hood as there is no magic happening in those frameworks.</p>\n<p>The complete code for this blog can be found at <a href=\"https://github.com/LoginRadius/engineering-blog-samples/tree/master/NodeJs/NodeHTTPServer\">Github Repo</a>.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n  .dark-default-dark {\n    background-color: #1E1E1E;\n    color: #D4D4D4;\n  }\n  .dark-default-dark .mtk1 { color: #D4D4D4; }\n  .dark-default-dark .mtk12 { color: #9CDCFE; }\n  .dark-default-dark .mtk17 { color: #808080; }\n  .dark-default-dark .mtk4 { color: #569CD6; }\n  .dark-default-dark .mtk8 { color: #CE9178; }\n  .dark-default-dark .mtk11 { color: #DCDCAA; }\n  .dark-default-dark .mtk7 { color: #B5CEA8; }\n  .dark-default-dark .mtk3 { color: #6A9955; }\n  .dark-default-dark .mtk15 { color: #C586C0; }\n  .dark-default-dark .mtk10 { color: #4EC9B0; }\n</style>","frontmatter":{"date":"November 27, 2020","updated_date":null,"description":"Let us understand the core http module in NodeJS, which is the basic building block of frameworks like ExpressJS etc.","title":"NodeJS Server using Core HTTP Module","tags":["NodeJs","JavaScript"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/8d8c41d9ba7fce1f1b5c6d72e0982463/58556/coverImage.webp","srcSet":"/static/8d8c41d9ba7fce1f1b5c6d72e0982463/61e93/coverImage.webp 200w,\n/static/8d8c41d9ba7fce1f1b5c6d72e0982463/1f5c5/coverImage.webp 400w,\n/static/8d8c41d9ba7fce1f1b5c6d72e0982463/58556/coverImage.webp 800w,\n/static/8d8c41d9ba7fce1f1b5c6d72e0982463/99238/coverImage.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Hridayesh Sharma","github":"vyasriday","avatar":null}}}},{"node":{"excerpt":"How does bitwise ^ (XOR) work? XOR is a bitwise operator, and it stands for \"exclusive or.\" It performs logical operation. If input bits are…","fields":{"slug":"/engineering/how-does-bitwise-xor-work/"},"html":"<h2 id=\"how-does-bitwise--xor-work\" style=\"position:relative;\"><a href=\"#how-does-bitwise--xor-work\" aria-label=\"how does bitwise  xor work permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How does bitwise ^ (XOR) work?</h2>\n<p>XOR is a bitwise operator, and it stands for \"exclusive or.\" It performs <strong>logical</strong> operation. If input bits are the same, then the output will be false(0) else true(1).</p>\n<p>XOR table:</p>\n<table>\n<thead>\n<tr>\n<th>X</th>\n<th>Y</th>\n<th>X^Y</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>0</td>\n<td>0</td>\n</tr>\n<tr>\n<td>0</td>\n<td>1</td>\n<td>1</td>\n</tr>\n<tr>\n<td>1</td>\n<td>0</td>\n<td>1</td>\n</tr>\n<tr>\n<td>1</td>\n<td>1</td>\n<td>0</td>\n</tr>\n</tbody>\n</table>\n<p>Example:  <code>4^3 = 7</code></p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"0\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk12\">In</span><span class=\"mtk1\"> binary: </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">\t     </span><span class=\"mtk7\">0100</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">\t   ^ </span><span class=\"mtk7\">0011</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">\t    ------</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> Result: </span><span class=\"mtk7\">0111</span><span class=\"mtk1\">  </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> (</span><span class=\"mtk7\">7</span><span class=\"mtk1\">)</span></span></code></pre>\n<h4 id=\"xor-with-negative-numbers\" style=\"position:relative;\"><a href=\"#xor-with-negative-numbers\" aria-label=\"xor with negative numbers permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>XOR with negative numbers</h4>\n<p>Let's understand with an example <code>-4^-2 = 2</code>\nIn the above example, we can see <code>-4^-2</code>output will be <code>2</code>\nbut the question arises how? Because if we represent both inputs in the binary form, then we do XOR of bits, then the output will be <code>0000 0110</code> and in decimal, it will be <code>6</code> but as we know output should be <code>2</code>.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"1\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk7\">1000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0100</span><span class=\"mtk1\"> (-</span><span class=\"mtk7\">4</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">^ </span><span class=\"mtk7\">1000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0010</span><span class=\"mtk1\"> (-</span><span class=\"mtk7\">2</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">------------------</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk7\">0000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0110</span><span class=\"mtk1\"> </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> (</span><span class=\"mtk7\">6</span><span class=\"mtk1\">) </span><span class=\"mtk3\">// incorrect output</span></span></code></pre>\n<blockquote>\n<p>Note: Here, the leftmost bit position is reserved for the sign of the\nvalue (positive or negative) and doesn't contribute towards the value of the number.</p>\n</blockquote>\n<p> Let's understand how the XOR operation works with negative numbers.</p>\n<h5 id=\"how-xor-operation-works-with-negative-numbers\" style=\"position:relative;\"><a href=\"#how-xor-operation-works-with-negative-numbers\" aria-label=\"how xor operation works with negative numbers permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How XOR operation works with negative numbers?</h5>\n<p>First, the XOR operation is to XOR each bit (the same is 0, the difference is 1), but you need to convert the number into a complement first.</p>\n<ol>\n<li>The complement of a positive number is itself</li>\n<li>\n<p>The complement of the negative number is reversed for each bit and then incremented by 1 (the highest is kept at 1)</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"2\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk3\">// Lets take -4</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">In</span><span class=\"mtk1\"> binary: \t\t\t</span><span class=\"mtk7\">1000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0100</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">Reverse: \t\t\t</span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1011</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk11\">complement</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">Increment</span><span class=\"mtk1\"> </span><span class=\"mtk12\">by</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1</span><span class=\"mtk1\">): \t</span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1100</span></span></code></pre>\n</li>\n</ol>\n<p>// Now -2\nIn binary: \t\t\t1000 0010\nReverse: \t\t\t1111 1101\ncomplement (Increment by 1): \t1111 1110</p>\n<p>Final result:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"3\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk12\">complement</span><span class=\"mtk1\"> </span><span class=\"mtk4\">of</span><span class=\"mtk1\"> -</span><span class=\"mtk7\">4</span><span class=\"mtk1\"> : </span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1100</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">complement</span><span class=\"mtk1\"> </span><span class=\"mtk4\">of</span><span class=\"mtk1\"> -</span><span class=\"mtk7\">2</span><span class=\"mtk1\"> : </span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1110</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">                  -----------</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">Result:            </span><span class=\"mtk7\">0000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0010</span><span class=\"mtk1\"> \t</span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> </span><span class=\"mtk7\">2</span></span></code></pre>\n<p><em>Here, the MSB bit of result will denote the sign, and the rest of the bits will denote the value of the final result.</em>\nXOR sign table could be useful to understand the sign of result:</p>\n<table>\n<thead>\n<tr>\n<th>X</th>\n<th>Y</th>\n<th>X^Y</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>+</td>\n<td>+</td>\n<td>+</td>\n</tr>\n<tr>\n<td>+</td>\n<td>-</td>\n<td>-</td>\n</tr>\n<tr>\n<td>-</td>\n<td>+</td>\n<td>-</td>\n</tr>\n<tr>\n<td>-</td>\n<td>-</td>\n<td>+</td>\n</tr>\n</tbody>\n</table>\n<p>The above approach will work with negative inputs, but if we have positive and negative, then? </p>\n<h5 id=\"how-xor-operation-works-with-positive-and-negative-numbers\" style=\"position:relative;\"><a href=\"#how-xor-operation-works-with-positive-and-negative-numbers\" aria-label=\"how xor operation works with positive and negative numbers permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How XOR operation works with positive and negative numbers?</h5>\n<p>Let's performs <code>-5 ^ 2</code>\nFollow the same above approach to get a complement code of <code>-5</code>.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"4\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk12\">complement</span><span class=\"mtk1\"> </span><span class=\"mtk4\">of</span><span class=\"mtk1\"> -</span><span class=\"mtk7\">5</span><span class=\"mtk1\"> :          </span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1011</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk3\">// Note: complement of a positive number is itself</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">complement</span><span class=\"mtk1\"> </span><span class=\"mtk4\">of</span><span class=\"mtk1\"> </span><span class=\"mtk7\">2</span><span class=\"mtk1\"> :           </span><span class=\"mtk7\">0000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0010</span><span class=\"mtk1\">  </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">complement</span><span class=\"mtk1\"> result:          </span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1001</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">Now</span><span class=\"mtk1\">, </span><span class=\"mtk12\">complement</span><span class=\"mtk1\"> </span><span class=\"mtk12\">result</span><span class=\"mtk1\"> -</span><span class=\"mtk7\">1</span><span class=\"mtk1\"> : </span><span class=\"mtk7\">1111</span><span class=\"mtk1\"> </span><span class=\"mtk7\">1000</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">                           -----------</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">Final</span><span class=\"mtk1\"> </span><span class=\"mtk11\">result</span><span class=\"mtk1\">(</span><span class=\"mtk12\">inverse</span><span class=\"mtk1\"> </span><span class=\"mtk12\">code</span><span class=\"mtk1\">): </span><span class=\"mtk7\">1000</span><span class=\"mtk1\"> </span><span class=\"mtk7\">0111</span><span class=\"mtk1\">   </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> -</span><span class=\"mtk7\">7</span></span></code></pre>\n<h4 id=\"some-interesting-use-cases-of-xor-operator\" style=\"position:relative;\"><a href=\"#some-interesting-use-cases-of-xor-operator\" aria-label=\"some interesting use cases of xor operator permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Some interesting use cases of XOR operator</h4>\n<ul>\n<li>\n<p>Swap two number without the third variable\nExample:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"5\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk4\">function</span><span class=\"mtk1\"> </span><span class=\"mtk11\">swapWithXOR</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">a</span><span class=\"mtk1\">, </span><span class=\"mtk12\">b</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">a</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">a</span><span class=\"mtk1\">^</span><span class=\"mtk12\">b</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">b</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">a</span><span class=\"mtk1\">^</span><span class=\"mtk12\">b</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">a</span><span class=\"mtk1\">=</span><span class=\"mtk12\">a</span><span class=\"mtk1\">^</span><span class=\"mtk12\">b</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk10\">console</span><span class=\"mtk1\">.</span><span class=\"mtk11\">log</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&quot;result =&gt; a: &quot;</span><span class=\"mtk1\"> + </span><span class=\"mtk12\">a</span><span class=\"mtk1\"> + </span><span class=\"mtk8\">&quot;, b: &quot;</span><span class=\"mtk1\"> + </span><span class=\"mtk12\">b</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk11\">swapWithXOR</span><span class=\"mtk1\">(</span><span class=\"mtk7\">4</span><span class=\"mtk1\">, </span><span class=\"mtk7\">1</span><span class=\"mtk1\">); </span><span class=\"mtk3\">// result =&gt; a: 1, b: 4</span></span></code></pre>\n</li>\n<li>RAID Drive Backups (Systems)</li>\n<li>Cryptography (XOR cipher)</li>\n<li>Array operations</li>\n</ul>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n  .dark-default-dark {\n    background-color: #1E1E1E;\n    color: #D4D4D4;\n  }\n  .dark-default-dark .mtk12 { color: #9CDCFE; }\n  .dark-default-dark .mtk1 { color: #D4D4D4; }\n  .dark-default-dark .mtk7 { color: #B5CEA8; }\n  .dark-default-dark .mtk4 { color: #569CD6; }\n  .dark-default-dark .mtk3 { color: #6A9955; }\n  .dark-default-dark .mtk11 { color: #DCDCAA; }\n  .dark-default-dark .mtk10 { color: #4EC9B0; }\n  .dark-default-dark .mtk8 { color: #CE9178; }\n</style>","frontmatter":{"date":"November 24, 2020","updated_date":null,"description":"Everything you should know about bitwise ^ xor operator.","title":"How does bitwise ^ (XOR) work?","tags":["bitwise","XOR"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/3dc791a9bfecb4dc03ef8263118ccf7d/58556/xor.webp","srcSet":"/static/3dc791a9bfecb4dc03ef8263118ccf7d/61e93/xor.webp 200w,\n/static/3dc791a9bfecb4dc03ef8263118ccf7d/1f5c5/xor.webp 400w,\n/static/3dc791a9bfecb4dc03ef8263118ccf7d/58556/xor.webp 800w,\n/static/3dc791a9bfecb4dc03ef8263118ccf7d/99238/xor.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Kheenvraj Lomror","github":"rajlomror","avatar":null}}}},{"node":{"excerpt":"A High-Level Introduction to Redux Saga Redux Saga is a middleware library used to allow a Redux store to interact with resources outside of…","fields":{"slug":"/engineering/introduction-to-redux-saga/"},"html":"<h2 id=\"a-high-level-introduction-to-redux-saga\" style=\"position:relative;\"><a href=\"#a-high-level-introduction-to-redux-saga\" aria-label=\"a high level introduction to redux saga permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>A High-Level Introduction to Redux Saga</h2>\n<p>Redux Saga is a middleware library used to allow a Redux store to interact with resources outside of itself asynchronously. This includes making HTTP requests to external services, accessing browser storage, and executing I/O operations. These operations are also known as side effects. Redux Saga helps to organize these side effects in a way that is easier to manage.</p>\n<h2 id=\"why-do-we-even-need-this\" style=\"position:relative;\"><a href=\"#why-do-we-even-need-this\" aria-label=\"why do we even need this permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why do we even need this?</h2>\n<p>A redux store natively only knows how to dispatch actions and update its state using its root reducer. Actions represent an event describing something happening in your application and an intention to change your application's state. A reducer accumulates values from or stemming from dispatched actions and accumulates these values into the newly updated state of your application.</p>\n<p>Reducers must be written as a pure function, as it is necessary to enable useful features of Redux such as time travel (replaying past actions). Actions are simply objects passed on into the reducer and are naturally deterministic. Thus we have a problem; there isn't any place in your Redux application to put your side effects in.</p>\n<h2 id=\"the-solution\" style=\"position:relative;\"><a href=\"#the-solution\" aria-label=\"the solution permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The solution</h2>\n<p>A Redux middleware lies between an action and a reducer. This enables actions to contain something else other than a plain object, as long as the middleware intercepts this, performs its logic, and returns a plain object to pass along to the reducer. </p>\n<p>Redux Thunk, a common alternative to Redux Saga, allows functions to be passed into the Redux store dispatch, which checks to see if it is a function or an action object, executing the function in the former case, and directly passing along the action object to the reducer in the latter case. These functions can then perform whatever complex asynchronous logic that it wants and produce a plain action object to be then passed into the reducer.</p>\n<p>Redux Sagas are slightly different in that a separate set of actions are defined in your Redux application, which is captured exclusively by watcher functions (as part of your saga). Upon capturing the action, the saga will execute the corresponding logic and dispatch a resultant action to your application's reducer. The saga essentially acts as a separate thread to your application, listening for specific actions from your main application to perform complex asynchronous tasks and updating your application's state once it is completed. </p>\n<h2 id=\"redux-saga-vs-alternatives\" style=\"position:relative;\"><a href=\"#redux-saga-vs-alternatives\" aria-label=\"redux saga vs alternatives permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Redux Saga vs. alternatives</h2>\n<p>While I wouldn't say Redux Saga is inherently better than any of the alternatives available, it does have a few benefits that might make you want to consider using it.</p>\n<p>Redux Saga offers a place completely decoupled from your action creators for you to handle your application's side effects. Some people may feel that this makes your application's data flow harder to follow (which I would agree with), but I think that this decoupling makes organizing your codebase and extending functionality easier down the road. </p>\n<p>For example, in a situation where you might need to support a workflow that requires multiple HTTP requests to different services in a particular order, Redux Saga allows you to compose granular sagas into a single one and represent this new high-level function with a separate action. Your application can still access each individual HTTP resource in other workflows, but for this particular one, your React component can simply call this high-level action to load whatever it needs from a single place. As far as your component is concerned, your asynchronous logic to load multiple resources in a particular order is abstracted away. </p>\n<p>Redux Saga also offers us a collection of helper functions that are used to spawn your tasks when some specific actions are dispatched. These can be used to help organize when and how your tasks are executed.</p>\n<p>For example, one of the most commonly used helper functions is <code>takeEvery()</code>. This instructs the middleware to spawn a new task for every action dispatched to your store matching a given pattern. This provides a behaviour similar to Redux Thunk and is as simple as it gets: \"Application tells you to fetch something, go fetch it\".</p>\n<p>Now imagine that you had two functionally independent components that needed to retrieve the most up to date data from the same place. Previously they existed on two different pages and could both be visited at any time. It would make sense for both components to try to retrieve a fresh copy of the resource whenever it is visited. Now imagine that your specification has changed, and now the two components need to exist on the same page. Now you have a situation where two different components are redundantly spawning the same task. </p>\n<p>Obviously, you could rewrite one of the components to no longer try to retrieve a fresh copy and rely on the other to create the necessary action to retrieve this resource and populate the application store. Or you could add some logic to ensure that your component does not try to create a new action to retrieve this resource if this resource is already being loaded. But this could also be solved using another Redux Saga helper function: <code>take()</code>. This function instructs the middleware to spawn a new task for an action dispatched matching a given pattern but will effectively ignore any new actions until the spawned task has been completed.</p>\n<p>With this, your two independent components can coexist together without changing any component-specific logic! As far as your component is concerned, it asks your saga to retrieve a resource on its behalf and retrieves it from the resultant updated state. Your saga gets to decide how it wants to handle two requests from different components.</p>\n<h2 id=\"concluding-thoughts\" style=\"position:relative;\"><a href=\"#concluding-thoughts\" aria-label=\"concluding thoughts permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Concluding thoughts</h2>\n<p>There is a fair bit more to Redux Saga than I managed to cram into this post. If you're interested in incorporating it into your project or want to know more, check out their fantastic documentation here: <a href=\"https://redux-saga.js.org/\">Redux-saga</a>. It's packed full of useful examples if you'd like to get into the low-level details.</p>\n<p>Redux Saga is one of many tools that can help you handle your application's side effects. It's heavy and has a learning curve but contains a lot of functionality that will help keep your codebase neat and modular.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n</style>","frontmatter":{"date":"November 23, 2020","updated_date":null,"description":"A high level introduction to Redux Saga.","title":"Introduction to Redux Saga","tags":["React","Redux","Redux Saga"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/4fec246c146752a9eaa62241dbbe219f/58556/unsplash.webp","srcSet":"/static/4fec246c146752a9eaa62241dbbe219f/61e93/unsplash.webp 200w,\n/static/4fec246c146752a9eaa62241dbbe219f/1f5c5/unsplash.webp 400w,\n/static/4fec246c146752a9eaa62241dbbe219f/58556/unsplash.webp 800w,\n/static/4fec246c146752a9eaa62241dbbe219f/99238/unsplash.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Nick Chim","github":"nickc95","avatar":null}}}},{"node":{"excerpt":"React thrives on being one of the premier tools to build single-page applications, which used to be a fairly foreign concept when I started…","fields":{"slug":"/engineering/react-router-basics/"},"html":"<p>React thrives on being one of the premier tools to build single-page applications, which used to be a fairly foreign concept when I started building my first React app. Back then, I was used to the concept of serving separate web pages whenever the user redirects from an URL path to another, and it was rather challenging at first to wrap my head around how React handles navigation.</p>\n<p>With that in mind, this blog post aims to lay down and explain the basic aspects of navigation using React Router, one of the most, if not the most, popular solutions for navigation within a React app.</p>\n<p>Throughout the first section below, please reference <a href=\"https://codepen.io/n-nguyen/pen/XWKwJXM\">this CodePen example</a>.</p>\n<ol>\n<li><strong>Link, Switch and Router</strong></li>\n</ol>\n<p>As hinted at in the preface of this writing, routing in React does not involve replacing the HTML, CSS or JavaScript resources currently being served or reloading the browser content. Instead, using libraries like <code>react-router</code> allows containers to be swapped in and out dynamically based on the current URL location, and this all happens client-side. With that in mind, React Router can more generally be understood as a wrapper that handles conditional rendering based on URL path.</p>\n<p>To accomplish this, the basic building blocks that developers get to play with are <code>&#x3C;Route></code>, <code>&#x3C;Switch></code> and <code>&#x3C;Link></code>. Let us look at a basic example making use of these 3 components:</p>\n<p>First off, let’s create some simple text components. These components are stand-ins for actual components to be swapped in and out in navigation. HelloBanner will be a div containing the simple message “Hello”, and WorldBanner containing “World!”:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"0\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk11\">HelloBanner</span><span class=\"mtk1\">: </span><span class=\"mtk10\">React</span><span class=\"mtk1\">.</span><span class=\"mtk10\">FunctionComponent</span><span class=\"mtk1\"> = () </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> (</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk1\"> </span><span class=\"mtk12\">id</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;banner_hello&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">className</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;banner&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Hello Banner is currently displayed. We are currently in path &quot;/hello&quot;</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  ) </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk4\">const</span><span class=\"mtk1\"> </span><span class=\"mtk11\">WorldBanner</span><span class=\"mtk1\">: </span><span class=\"mtk10\">React</span><span class=\"mtk1\">.</span><span class=\"mtk10\">FunctionComponent</span><span class=\"mtk1\"> = () </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> (</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk1\"> </span><span class=\"mtk12\">id</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;banner_world&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">className</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;banner&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Hello Banner is currently displayed. We are currently in path &quot;/world&quot;</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  ) </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span></code></pre>\n<p>Now let’s imagine the layout of a conventional web application with a top navigation bar. The navigation bar contains links to each section of the app and the body would show the content of the current webpage. The skeleton code for that container would look something like this in React:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"1\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk4\">class</span><span class=\"mtk1\"> </span><span class=\"mtk10\">AppContainer</span><span class=\"mtk1\"> </span><span class=\"mtk4\">extends</span><span class=\"mtk1\"> </span><span class=\"mtk10\">Component</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">constructor</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">super</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk11\">render</span><span class=\"mtk1\">() {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> (</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk1\"> </span><span class=\"mtk12\">id</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;div_app_container&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">className</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;app-container&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk1\"> </span><span class=\"mtk12\">id</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;div_nav&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">className</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;nav-bar&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Navigation bar</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Link</span><span class=\"mtk1\"> </span><span class=\"mtk12\">to</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/hello&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Link to /hello</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Link</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Link</span><span class=\"mtk1\"> </span><span class=\"mtk12\">to</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/world&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Link to /world</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Link</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Link</span><span class=\"mtk1\"> </span><span class=\"mtk12\">to</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/clearlyinvalidpath&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Link to a clearly invalid path.</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Link</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk1\"> </span><span class=\"mtk12\">id</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;main_container&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">className</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;main-container&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">Main Container</span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Switch</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Route</span><span class=\"mtk1\"> </span><span class=\"mtk12\">exact</span><span class=\"mtk1\"> </span><span class=\"mtk12\">path</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">              </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">                </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">                  Default container. We are in root path</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">                </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">span</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">              </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Route</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Route</span><span class=\"mtk1\"> </span><span class=\"mtk12\">path</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/hello&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk12\">component</span><span class=\"mtk1\">=</span><span class=\"mtk4\">{</span><span class=\"mtk12\">HelloBanner</span><span class=\"mtk4\">}</span><span class=\"mtk1\"> </span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Route</span><span class=\"mtk1\"> </span><span class=\"mtk12\">path</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/world&quot;</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">              </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">WorldBanner</span><span class=\"mtk1\"> </span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Route</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">            </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Redirect</span><span class=\"mtk1\"> </span><span class=\"mtk12\">to</span><span class=\"mtk1\">=</span><span class=\"mtk8\">&quot;/&quot;</span><span class=\"mtk1\"> </span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">          </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Switch</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">        </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk4\">div</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    );</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk12\">ReactDOM</span><span class=\"mtk1\">.</span><span class=\"mtk11\">render</span><span class=\"mtk1\">(</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">BrowserRouter</span><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">AppContainer</span><span class=\"mtk1\"> </span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">BrowserRouter</span><span class=\"mtk17\">&gt;</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk12\">document</span><span class=\"mtk1\">.</span><span class=\"mtk11\">getElementById</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&quot;app&quot;</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">);</span></span></code></pre>\n<p>If you are currently looking at the render of this structure from the CodePen, you would see this very simple UI:</p>\n<p><img src=\"/a0ae6207fefc74ee8f42e98d08082ff6/image1.webp\" alt=\"Example UI\"></p>\n<p>Clicking on the <code>&#x3C;Link></code>’s in the navigation bar will “navigate” you to the corresponding paths. In effect, what this does is twofold:</p>\n<ul>\n<li>Updating the current path of the browser to the indicated path.</li>\n<li>Update all <code>&#x3C;Route></code> components to rerender according to the current path.</li>\n</ul>\n<p>This is demonstrated through the example app. Once you click the links to /hello or to /world, the corresponding component will be swapped in under the <code>&#x3C;Switch></code> container.</p>\n<p>A couple of noteworthy things from the code example:</p>\n<ul>\n<li><code>&#x3C;Switch></code> component allows swapping between <code>&#x3C;Route></code>’s and render the correct component with a given URL path. However, <code>&#x3C;Route></code> components do not have to be wrapped inside a <code>&#x3C;Switch></code>. While standalone, a <code>&#x3C;Route></code> will simply render when the URL path matches its own <code>path</code> prop.</li>\n<li>The <code>&#x3C;Redirect></code> component at the end acts as the default route. In case none of the other routes match with the current URL path, it simply redirects the user back to root.</li>\n<li><strong>Redirecting programmatically</strong></li>\n</ul>\n<p>The workflow described above is intuitive from the end user’s point of view. However, there are times when the application’s internal logic demands a redirection to be performed following app events. In these occasions, React Router leverages the <a href=\"https://reactrouter.com/web/api/history\"><code>history</code></a> object to allow for programmatic redirection:</p>\n<p>For a traditional setup, the <code>history</code> object can be accessed through a component’s props through the user of the <code>withRouter</code> higher order component: </p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"2\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk15\">import</span><span class=\"mtk1\"> </span><span class=\"mtk4\">*</span><span class=\"mtk1\"> </span><span class=\"mtk15\">as</span><span class=\"mtk1\"> </span><span class=\"mtk12\">React</span><span class=\"mtk1\"> </span><span class=\"mtk15\">from</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;react&quot;</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">import</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">RouteComponentProps</span><span class=\"mtk1\">, </span><span class=\"mtk12\">withRouter</span><span class=\"mtk1\"> } </span><span class=\"mtk15\">from</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;react-router-dom&quot;</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk4\">interface</span><span class=\"mtk1\"> </span><span class=\"mtk10\">SampleComponentProps</span><span class=\"mtk1\"> </span><span class=\"mtk4\">extends</span><span class=\"mtk1\"> </span><span class=\"mtk10\">RouteComponentProps</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// props go here</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk4\">interface</span><span class=\"mtk1\"> </span><span class=\"mtk10\">SampleComponentStateState</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// states go here</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk4\">class</span><span class=\"mtk1\"> </span><span class=\"mtk10\">SampleComponent</span><span class=\"mtk1\"> </span><span class=\"mtk4\">extends</span><span class=\"mtk1\"> </span><span class=\"mtk10\">React</span><span class=\"mtk1\">.</span><span class=\"mtk10\">Component</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">SampleComponentProps</span><span class=\"mtk1\">, </span><span class=\"mtk10\">SampleComponentStateState</span><span class=\"mtk1\">&gt; {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">constructor</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">: </span><span class=\"mtk10\">any</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">super</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk11\">performRedirect</span><span class=\"mtk1\"> = () </span><span class=\"mtk4\">=&gt;</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">history</span><span class=\"mtk1\"> } = </span><span class=\"mtk4\">this</span><span class=\"mtk1\">.</span><span class=\"mtk12\">props</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">history</span><span class=\"mtk1\">.</span><span class=\"mtk11\">push</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&quot;/desired-pathname&quot;</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk11\">render</span><span class=\"mtk1\">() {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk15\">default</span><span class=\"mtk1\"> </span><span class=\"mtk11\">withRouter</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">SampleComponentProps</span><span class=\"mtk1\">&gt;(</span><span class=\"mtk12\">SampleComponent</span><span class=\"mtk1\">);</span></span></code></pre>\n<p>In the example above, you can see all the components required to extract the <code>history</code> object, as well as the <code>history.push()</code> call to perform the redirection.</p>\n<p>For a more updated approach, React Router introduced the hook <a href=\"https://reactrouter.com/web/api/Hooks/usehistory\"><code>useHistory</code></a>, which should blend in more naturally when programming with a React Hooks intensive workflow.</p>\n<ol start=\"3\">\n<li><strong>Passing states on redirects</strong></li>\n</ol>\n<p>Certain redirects are unique in nature, and/or contain certain information about the previous user activity that you might want to pass on to the new component. In this case, the information can be passed through history states into the new component, which will then perform custom behavior based on these states:</p>\n<p>When using <code>&#x3C;Link></code> component redirect, populate the <code>to</code> prop with an object that contains the new path as well as states, instead of just the string for pathname:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"3\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk17\">&lt;</span><span class=\"mtk10\">Link</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk12\">to</span><span class=\"mtk1\">=</span><span class=\"mtk4\">{</span><span class=\"mtk1\">{</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">pathname:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;/desired-pathname&quot;</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">state:</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk12\">stateName:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;state to be passed.&quot;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span><span class=\"mtk4\">}</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  Link text here.</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk17\">&lt;/</span><span class=\"mtk10\">Link</span><span class=\"mtk17\">&gt;</span></span></code></pre>\n<p>The same object can be used as argument to the <code>history.push()</code> call to achieve similar results:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"4\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk12\">history</span><span class=\"mtk1\">.</span><span class=\"mtk11\">push</span><span class=\"mtk1\">({</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk12\">pathname:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;/desired-pathname&quot;</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk12\">state:</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk12\">stateName:</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;state to be passed.&quot;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">})</span></span></code></pre>\n<p>Once the state has been included with the redirection, on the receiving end, you can extract the state from the <code>history.location.state</code> object:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"javascript\" data-index=\"5\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk15\">import</span><span class=\"mtk1\"> </span><span class=\"mtk4\">*</span><span class=\"mtk1\"> </span><span class=\"mtk15\">as</span><span class=\"mtk1\"> </span><span class=\"mtk12\">React</span><span class=\"mtk1\"> </span><span class=\"mtk15\">from</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;react&quot;</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">import</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">RouteComponentProps</span><span class=\"mtk1\">, </span><span class=\"mtk12\">withRouter</span><span class=\"mtk1\"> } </span><span class=\"mtk15\">from</span><span class=\"mtk1\"> </span><span class=\"mtk8\">&quot;react-router-dom&quot;</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk4\">interface</span><span class=\"mtk1\"> </span><span class=\"mtk10\">ReceivingComponentProps</span><span class=\"mtk1\"> </span><span class=\"mtk4\">extends</span><span class=\"mtk1\"> </span><span class=\"mtk10\">RouteComponentProps</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// props go here</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk4\">interface</span><span class=\"mtk1\"> </span><span class=\"mtk10\">ReceivingComponentStateState</span><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk3\">// states go here</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk4\">class</span><span class=\"mtk1\"> </span><span class=\"mtk10\">ReceivingComponent</span><span class=\"mtk1\"> </span><span class=\"mtk4\">extends</span><span class=\"mtk1\"> </span><span class=\"mtk10\">React</span><span class=\"mtk1\">.</span><span class=\"mtk10\">Component</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">ReceivingComponentProps</span><span class=\"mtk1\">, </span><span class=\"mtk10\">ReceivingComponentStateState</span><span class=\"mtk1\">&gt; {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk4\">constructor</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">: </span><span class=\"mtk10\">any</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">super</span><span class=\"mtk1\">(</span><span class=\"mtk12\">props</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk11\">componentDidMount</span><span class=\"mtk1\">() {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk4\">const</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">history</span><span class=\"mtk1\"> } = </span><span class=\"mtk4\">this</span><span class=\"mtk1\">.</span><span class=\"mtk12\">props</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">history</span><span class=\"mtk1\">.</span><span class=\"mtk12\">location</span><span class=\"mtk1\">.</span><span class=\"mtk12\">state</span><span class=\"mtk1\"> && </span><span class=\"mtk12\">history</span><span class=\"mtk1\">.</span><span class=\"mtk12\">location</span><span class=\"mtk1\">.</span><span class=\"mtk12\">state</span><span class=\"mtk1\">.</span><span class=\"mtk12\">stateName</span><span class=\"mtk1\">) {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk3\">// stateName can be accessed here if it is passed in from a previous redirect action.</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">      </span><span class=\"mtk10\">console</span><span class=\"mtk1\">.</span><span class=\"mtk11\">log</span><span class=\"mtk1\">(</span><span class=\"mtk12\">history</span><span class=\"mtk1\">.</span><span class=\"mtk12\">location</span><span class=\"mtk1\">.</span><span class=\"mtk12\">state</span><span class=\"mtk1\">.</span><span class=\"mtk12\">stateName</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  </span><span class=\"mtk11\">render</span><span class=\"mtk1\">() {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">    </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> </span><span class=\"mtk17\">&lt;</span><span class=\"mtk4\">div</span><span class=\"mtk17\">/&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">  }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">}</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk15\">export</span><span class=\"mtk1\"> </span><span class=\"mtk15\">default</span><span class=\"mtk1\"> </span><span class=\"mtk11\">withRouter</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">ReceivingComponentProps</span><span class=\"mtk1\">&gt;(</span><span class=\"mtk12\">ReceivingComponent</span><span class=\"mtk1\">);</span></span></code></pre>\n<p>The state access is in <code> componentDidMount</code> in the example above.</p>\n<ol start=\"4\">\n<li><strong>Parting Words</strong></li>\n</ol>\n<p>At this point, hopefully, we have covered all the big bullet points to help you get started with navigation using React Router. I hope this write-up has been informative and helpful to your understanding of navigation in React, as well as helping you build your next React application.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n  .dark-default-dark {\n    background-color: #1E1E1E;\n    color: #D4D4D4;\n  }\n  .dark-default-dark .mtk4 { color: #569CD6; }\n  .dark-default-dark .mtk1 { color: #D4D4D4; }\n  .dark-default-dark .mtk11 { color: #DCDCAA; }\n  .dark-default-dark .mtk10 { color: #4EC9B0; }\n  .dark-default-dark .mtk15 { color: #C586C0; }\n  .dark-default-dark .mtk17 { color: #808080; }\n  .dark-default-dark .mtk12 { color: #9CDCFE; }\n  .dark-default-dark .mtk8 { color: #CE9178; }\n  .dark-default-dark .mtk3 { color: #6A9955; }\n</style>","frontmatter":{"date":"November 20, 2020","updated_date":null,"description":"Everything essential you need to know about React Router.","title":"React Router Basics: Routing in a Single-page Application","tags":["JavaScript","Node","React","React Router"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/4bcd64f320b4486ea6ddb7147ff85a96/58556/index.webp","srcSet":"/static/4bcd64f320b4486ea6ddb7147ff85a96/61e93/index.webp 200w,\n/static/4bcd64f320b4486ea6ddb7147ff85a96/1f5c5/index.webp 400w,\n/static/4bcd64f320b4486ea6ddb7147ff85a96/58556/index.webp 800w,\n/static/4bcd64f320b4486ea6ddb7147ff85a96/99238/index.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Nathan Nguyen","github":"nathannguyenn","avatar":null}}}},{"node":{"excerpt":"Introduction Hello Everyone, In this article, we will learn how to send emails in .NET/C# using SMTP. As sometimes, it is required to send…","fields":{"slug":"/engineering/how-to-send-emails-through-csharp-dotnet-using-smtp/"},"html":"<h2 id=\"introduction\" style=\"position:relative;\"><a href=\"#introduction\" aria-label=\"introduction permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Introduction</h2>\n<p>Hello Everyone, In this article, we will learn how to send emails in .NET/C# using SMTP. As sometimes, it is required to send emails to the users of the application. Email communication is considered a good way to communicate with the users of the application. There are different ways to send emails in .NET, but here we will talk about SMTP.</p>\n<h2 id=\"what-is-smtp\" style=\"position:relative;\"><a href=\"#what-is-smtp\" aria-label=\"what is smtp permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is SMTP?</h2>\n<p>SMTP stands for Simple Mail Transfer Protocol. It is a communication protocol for electronic mail transmission. Mail servers and other message transfer agents use SMTP to send and receive mail messages. The Key Features of SMTP are it is considered a reliable server for sending emails, and it delivers the email more easily and quickly as it is developed from a simple platform.</p>\n<h2 id=\"prerequisites\" style=\"position:relative;\"><a href=\"#prerequisites\" aria-label=\"prerequisites permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Prerequisites</h2>\n<ul>\n<li>Basic knowledge about the C#/.NET and it's application IDE</li>\n</ul>\n<h2 id=\"lets-start\" style=\"position:relative;\"><a href=\"#lets-start\" aria-label=\"lets start permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Let's start</h2>\n<p>In the implementation part, we will first create a .NET Core class library, and then we will use that library in the .NET Core console app.</p>\n<p><strong>Step 1</strong> - Create a .NET Core Console App project in IDE.</p>\n<p><strong>Step 2</strong> - Add a .NET Core class library in the created solution.</p>\n<p><strong>Step 3</strong> - Create a new class file in the class library and name it as MailArguments.cs. Add the arguments fields in this file, which will be used in sending the email.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"0\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">MailTo</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Bcc</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Name</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Subject</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Message</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">SmtpHost</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Password</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">int</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Port</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk12\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">MailFrom</span><span class=\"mtk1\"> { </span><span class=\"mtk12\">get</span><span class=\"mtk1\">; </span><span class=\"mtk12\">set</span><span class=\"mtk1\">; }</span></span></code></pre>\n<p><strong>Step 4</strong> - Create a new class file in the class library; name it ExtensionMethods.cs. Here we will add the extension methods, which will be helpful to put the validation while sending the emails.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"1\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk4\">static</span><span class=\"mtk1\"> </span><span class=\"mtk4\">bool</span><span class=\"mtk1\"> </span><span class=\"mtk11\">IsNotNullOrEmpty</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">T</span><span class=\"mtk1\">&gt;(</span><span class=\"mtk4\">this</span><span class=\"mtk1\"> </span><span class=\"mtk10\">IEnumerable</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">T</span><span class=\"mtk1\">&gt; </span><span class=\"mtk12\">value</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> </span><span class=\"mtk12\">value</span><span class=\"mtk1\"> != </span><span class=\"mtk4\">null</span><span class=\"mtk1\"> && </span><span class=\"mtk12\">value</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Any</span><span class=\"mtk1\">(); </span><span class=\"mtk3\">// This will return true if the value is not null and not empty</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk4\">static</span><span class=\"mtk1\"> </span><span class=\"mtk4\">bool</span><span class=\"mtk1\"> </span><span class=\"mtk11\">IsNotNullOrEmptyOrWhiteSpace</span><span class=\"mtk1\">(</span><span class=\"mtk4\">this</span><span class=\"mtk1\"> </span><span class=\"mtk4\">string</span><span class=\"mtk1\"> </span><span class=\"mtk12\">value</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> !(</span><span class=\"mtk12\">string</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNullOrEmpty</span><span class=\"mtk1\">(</span><span class=\"mtk12\">value</span><span class=\"mtk1\">) || </span><span class=\"mtk12\">string</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNullOrWhiteSpace</span><span class=\"mtk1\">(</span><span class=\"mtk12\">value</span><span class=\"mtk1\">)); </span><span class=\"mtk3\">// This will return true if the string value is not null, not empty and not contains any white space</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk4\">static</span><span class=\"mtk1\"> </span><span class=\"mtk4\">bool</span><span class=\"mtk1\"> </span><span class=\"mtk11\">IsNotNull</span><span class=\"mtk1\">(</span><span class=\"mtk4\">this</span><span class=\"mtk1\"> </span><span class=\"mtk4\">object</span><span class=\"mtk1\"> </span><span class=\"mtk12\">value</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> </span><span class=\"mtk12\">value</span><span class=\"mtk1\"> != </span><span class=\"mtk4\">null</span><span class=\"mtk1\">; </span><span class=\"mtk3\">// This will return true if the object value is not null</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span></code></pre>\n<p>Resolve missing references.</p>\n<p><strong>Step 5</strong> - Create a new static class file in the class library name it as Mail.cs. In this class add a static method with try and catch block.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"2\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">public</span><span class=\"mtk1\"> </span><span class=\"mtk4\">static</span><span class=\"mtk1\"> </span><span class=\"mtk10\">Tuple</span><span class=\"mtk1\">&lt;</span><span class=\"mtk4\">bool</span><span class=\"mtk1\">, </span><span class=\"mtk4\">string</span><span class=\"mtk1\">&gt; </span><span class=\"mtk11\">SendEMail</span><span class=\"mtk1\">(</span><span class=\"mtk10\">MailArguments</span><span class=\"mtk1\"> </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">, </span><span class=\"mtk10\">List</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">Attachment</span><span class=\"mtk1\">&gt; </span><span class=\"mtk12\">attachments</span><span class=\"mtk1\">, </span><span class=\"mtk4\">bool</span><span class=\"mtk1\"> </span><span class=\"mtk12\">isSsl</span><span class=\"mtk1\">, </span><span class=\"mtk10\">Dictionary</span><span class=\"mtk1\">&lt;</span><span class=\"mtk4\">string</span><span class=\"mtk1\">, </span><span class=\"mtk4\">string</span><span class=\"mtk1\">&gt; </span><span class=\"mtk12\">headers</span><span class=\"mtk1\">){</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk15\">try</span><span class=\"mtk1\">{</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk15\">catch</span><span class=\"mtk1\"> (</span><span class=\"mtk10\">Exception</span><span class=\"mtk1\"> </span><span class=\"mtk12\">ex</span><span class=\"mtk1\">){</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">msg</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">ex</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Message</span><span class=\"mtk1\">;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">return</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Tuple</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Create</span><span class=\"mtk1\">(</span><span class=\"mtk4\">false</span><span class=\"mtk1\">, </span><span class=\"mtk12\">msg</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span></code></pre>\n<p>Resolve missing references.</p>\n<p>In this method, we are returning the Tuple&#x3C;bool, string> which returns the status of the email sent and a message from the method in case of failure and success.</p>\n<p><strong>Step 7</strong> - Add below lines of code which will help create the NetworkCredentials for SMTP in the created method SendEmail.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"3\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">networkCredential</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">NetworkCredential</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Password</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Password</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">UserName</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">MailFrom</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span></code></pre>\n<p>Here we are using NetworkCredential class to set the UserName and Password.</p>\n<p><strong>Step 8</strong> - Add below lines of code, which will be used to initiate a message, subject, and IsBodyHtml.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"4\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">MailMessage</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Body</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Message</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Subject</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Subject</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">IsBodyHtml</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">true</span><span class=\"mtk1\"> </span><span class=\"mtk3\">// This indicates that message body contains the HTML part as well.</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">.</span><span class=\"mtk12\">To</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Add</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">MailTo</span><span class=\"mtk1\">);</span></span></code></pre>\n<ul>\n<li>IsBodyHtml Indicates the message body contains the HTML part or not. If it’s true means, the HTML body contains in the message body.</li>\n</ul>\n<p><strong>Step 9</strong> - Add the below lines of code to check and add the Headers, BCC, and Attachments. Here we have used the earlier created extension methods to add the validation.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"5\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">headers</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNotNullOrEmpty</span><span class=\"mtk1\">() )</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">foreach</span><span class=\"mtk1\"> (</span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">header</span><span class=\"mtk1\"> </span><span class=\"mtk15\">in</span><span class=\"mtk1\"> </span><span class=\"mtk12\">headers</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Headers</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Add</span><span class=\"mtk1\">(</span><span class=\"mtk12\">header</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Key</span><span class=\"mtk1\">, </span><span class=\"mtk12\">header</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Value</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Bcc</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNotNullOrEmptyOrWhiteSpace</span><span class=\"mtk1\">())</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk4\">string</span><span class=\"mtk1\">[] </span><span class=\"mtk12\">bccIds</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Bcc</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Split</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&#39;,&#39;</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">bccIds</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNotNullOrEmpty</span><span class=\"mtk1\">())</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         </span><span class=\"mtk15\">foreach</span><span class=\"mtk1\"> (</span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">bcc</span><span class=\"mtk1\"> </span><span class=\"mtk15\">in</span><span class=\"mtk1\"> </span><span class=\"mtk12\">bccIds</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">             </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Bcc</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Add</span><span class=\"mtk1\">(</span><span class=\"mtk12\">bcc</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">attachments</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNotNull</span><span class=\"mtk1\">())</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk15\">foreach</span><span class=\"mtk1\"> (</span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">attachment</span><span class=\"mtk1\"> </span><span class=\"mtk15\">in</span><span class=\"mtk1\"> </span><span class=\"mtk12\">attachments</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         </span><span class=\"mtk15\">if</span><span class=\"mtk1\"> (</span><span class=\"mtk12\">attachment</span><span class=\"mtk1\">.</span><span class=\"mtk11\">IsNotNull</span><span class=\"mtk1\">())</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">             </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Attachments</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Add</span><span class=\"mtk1\">(</span><span class=\"mtk12\">attachment</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">         }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> }</span></span></code></pre>\n<p><strong>Step 10</strong> - Add below the line of code to create a new email address using the From and Name fields of MailArguments class.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"6\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">.</span><span class=\"mtk12\">From</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk11\">MailAddress</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">MailFrom</span><span class=\"mtk1\">, </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Name</span><span class=\"mtk1\">);</span></span></code></pre>\n<p><strong>Step 11</strong> - Add below lines of code to create a new SMTP client and use the send method of that client. When the email is successfully sent then we are creating a new tuple for sending the success message with a true flag that will indicate mail is sent.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"7\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">smtpClient</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">SmtpClient</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">SmtpHost</span><span class=\"mtk1\">)</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Port</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">Convert</span><span class=\"mtk1\">.</span><span class=\"mtk11\">ToInt32</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Port</span><span class=\"mtk1\">),</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">EnableSsl</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">isSsl</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">DeliveryMethod</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">SmtpDeliveryMethod</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Network</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">UseDefaultCredentials</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">false</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Credentials</span><span class=\"mtk1\"> = </span><span class=\"mtk12\">networkCredential</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk12\">smtpClient</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Send</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailMsg</span><span class=\"mtk1\">);</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk10\">return</span><span class=\"mtk1\"> </span><span class=\"mtk10\">Tuple</span><span class=\"mtk1\">.</span><span class=\"mtk11\">Create</span><span class=\"mtk1\">(true, &quot;</span><span class=\"mtk10\">Email</span><span class=\"mtk1\"> </span><span class=\"mtk12\">Sent</span><span class=\"mtk1\"> Successfully.&quot;);</span></span></code></pre>\n<p>Here we are initializing the below variables for the SMTP client.</p>\n<ul>\n<li>Port - Port of the SMTP client.</li>\n<li>EnableSSL - SSL stands for Secure Sockets Layer. SSL is commonly used for encrypting communications over the internet.</li>\n<li>\n<p>DeliveryMethod - Delivery Method are 3 types. Here we have used the Network type.</p>\n<ul>\n<li>Network: The message is sent via the network to the SMTP server.</li>\n<li>PickupDirectoryFromIis: The message is copied to the default mail directory of the Internet Information Services (IIS).</li>\n<li>SpecifiedPickupDirectory: The message is copied to the directory specified by the property PickupDirectoryLocation.</li>\n</ul>\n</li>\n<li>UseDefaultCredentials - true if the default credentials are used; otherwise false. Here we are not using default credentials. We are passing the credentials in the Credentials property.</li>\n<li>Credentials - The credentials which we have initialized above.</li>\n</ul>\n<p><strong>Step 12</strong> - In the Program.cs, which will be in the console app project, we will initialize and add the Mail arguments which are required to send an email.</p>\n<p><strong>Step 13</strong> - Before that add the reference of the class library which we have created above in your console app by doing the below steps</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"8\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">Right-click on the console app project-&gt;Click on Add-&gt;Click on Reference-&gt;Select the created class library project.</span></code></pre>\n<p><strong>Step 14</strong> - In the main method, add the below lines to initialize the arguments. Here I am using Gmail's SMTP server port and host address.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"9\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk4\">var</span><span class=\"mtk1\"> </span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">MailArguments</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">MailFrom</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--From mail address from where mail should be sent--&gt;&quot;</span><span class=\"mtk1\">,  </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Password</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--From mail address password--&gt;&quot;</span><span class=\"mtk1\">,  </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Name</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--From mail address name--&gt;&quot;</span><span class=\"mtk1\">,</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">MailTo</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--To mail address to where mail should be received--&gt;&quot;</span><span class=\"mtk1\">, </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Subject</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--Subject of the email--&gt;&quot;</span><span class=\"mtk1\">,                             </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Message</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--Message body of the email can contains HTML as well--&gt;&quot;</span><span class=\"mtk1\">,                                           </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Port</span><span class=\"mtk1\"> = </span><span class=\"mtk7\">587</span><span class=\"mtk1\">,                                                         </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">SmtpHost</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;smtp.gmail.com&quot;</span><span class=\"mtk1\">,                                                                     </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk12\">Bcc</span><span class=\"mtk1\"> = </span><span class=\"mtk8\">&quot;&lt;--BCC email id&#39;s separated by semicolon (;)--&gt;&quot;</span><span class=\"mtk1\">             </span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk10\">List</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">Attachment</span><span class=\"mtk1\">&gt; </span><span class=\"mtk12\">lstAttachments</span><span class=\"mtk1\">=</span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">List</span><span class=\"mtk1\">&lt;</span><span class=\"mtk10\">Attachment</span><span class=\"mtk1\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">Attachment</span><span class=\"mtk1\">(</span><span class=\"mtk8\">&quot;&lt;--Path of the attachment--&gt;&gt;&quot;</span><span class=\"mtk1\">,</span><span class=\"mtk12\">MediaTypeNames</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Image</span><span class=\"mtk1\">.</span><span class=\"mtk12\">Gif</span><span class=\"mtk1\">) </span><span class=\"mtk3\">//MediaType and Path of the attachment here I have selected Gif Image we have MediaTypeNames Application/Image/Text</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk10\">Dictionary</span><span class=\"mtk1\">&lt;</span><span class=\"mtk4\">string</span><span class=\"mtk1\">, </span><span class=\"mtk4\">string</span><span class=\"mtk1\">&gt; </span><span class=\"mtk12\">dictHeaders</span><span class=\"mtk1\"> = </span><span class=\"mtk4\">new</span><span class=\"mtk1\"> </span><span class=\"mtk10\">Dictionary</span><span class=\"mtk1\">&lt;</span><span class=\"mtk4\">string</span><span class=\"mtk1\">, </span><span class=\"mtk4\">string</span><span class=\"mtk1\">&gt;</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> {</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\">     { </span><span class=\"mtk8\">&quot;&lt;--Key of the header--&gt;&quot;</span><span class=\"mtk1\">, </span><span class=\"mtk8\">&quot;&lt;--Values of the header--&gt;&quot;</span><span class=\"mtk1\"> }</span></span>\n<span class=\"grvsc-line\"><span class=\"mtk1\"> };</span></span></code></pre>\n<p>Resolve missing references.</p>\n<p>You have to initialize all the variables as described above. From and Password will be the Gmail's account email id and password respectively because we are using Gmail's SMTP server.</p>\n<p>In the attachment, I have used the <em>MediaTypeNames.Image.Gif</em>, which is used for Gif Images. There are different constructors for the attachment class. For reference, you can read from here- <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.attachment\">Attachment Class</a>. Attachments are not necessary to be passed. You can pass null in the SendMail method below.</p>\n<p>Headers are custom headers that will be sent with the email. It is not necessary to pass these headers. You can pass null in the SendMail method below.</p>\n<p><strong>Step 15</strong> - Add the below line of code to call the SendMail method of the class library.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"c#\" data-index=\"10\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"><span class=\"mtk1\"> </span><span class=\"mtk12\">Console</span><span class=\"mtk1\">.</span><span class=\"mtk11\">WriteLine</span><span class=\"mtk1\">(</span><span class=\"mtk12\">Mail</span><span class=\"mtk1\">.</span><span class=\"mtk11\">SendEMail</span><span class=\"mtk1\">(</span><span class=\"mtk12\">mailArgs</span><span class=\"mtk1\">, </span><span class=\"mtk12\">lstAttachments</span><span class=\"mtk1\">, </span><span class=\"mtk4\">true</span><span class=\"mtk1\">, </span><span class=\"mtk12\">dictHeaders</span><span class=\"mtk1\">).</span><span class=\"mtk12\">Item2</span><span class=\"mtk1\">);</span></span></code></pre>\n<h3 id=\"note\" style=\"position:relative;\"><a href=\"#note\" aria-label=\"note permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Note</h3>\n<p>Here we have used Gmail's SMTP server to send emails (From Mail Address) so we have to enable the Less Secure Apps in our from mail address account by enabling <a href=\"https://www.google.com/settings/security/lesssecureapps\">Allow less secure apps</a> else we will get the error from Gmail's SMTP server (The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.)</p>\n<h2 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Conclusion</h2>\n<p>In this article, we have learned about how to How to send emails through C#/.NET using SMTP. We have used the class library to initiate in the console app to send a mail to the particular emailId.The complete code for this blog can be found at <a href=\"https://github.com/LoginRadius/engineering-blog-samples/tree/master/DotNet/SMTPSendEmail\">Github Repo</a>.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n  .dark-default-dark {\n    background-color: #1E1E1E;\n    color: #D4D4D4;\n  }\n  .dark-default-dark .mtk1 { color: #D4D4D4; }\n  .dark-default-dark .mtk4 { color: #569CD6; }\n  .dark-default-dark .mtk12 { color: #9CDCFE; }\n  .dark-default-dark .mtk11 { color: #DCDCAA; }\n  .dark-default-dark .mtk10 { color: #4EC9B0; }\n  .dark-default-dark .mtk15 { color: #C586C0; }\n  .dark-default-dark .mtk3 { color: #6A9955; }\n  .dark-default-dark .mtk8 { color: #CE9178; }\n  .dark-default-dark .mtk7 { color: #B5CEA8; }\n</style>","frontmatter":{"date":"November 19, 2020","updated_date":null,"description":" In this article, we will learn how to send emails in .NET/C# using SMTP","title":"How to send emails in C#/.NET using SMTP","tags":[".NET","C#","SMTP"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.3333333333333333,"src":"/static/0def756cf8634c19ffe25f2d6fc37dbd/58556/coverimage.webp","srcSet":"/static/0def756cf8634c19ffe25f2d6fc37dbd/61e93/coverimage.webp 200w,\n/static/0def756cf8634c19ffe25f2d6fc37dbd/1f5c5/coverimage.webp 400w,\n/static/0def756cf8634c19ffe25f2d6fc37dbd/58556/coverimage.webp 800w,\n/static/0def756cf8634c19ffe25f2d6fc37dbd/99238/coverimage.webp 1200w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Hemant Manwani","github":"hemant404","avatar":null}}}}]},"markdownRemark":{"excerpt":"Introduction Ever wondered how apps like Spotify, Netflix, or Slack manage seamless login experiences across devices? Many of them use JWT…","fields":{"slug":"/engineering/how-to-integrate-jwt/"},"html":"<h2 id=\"introduction\" style=\"position:relative;\"><a href=\"#introduction\" aria-label=\"introduction permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Introduction</h2>\n<p>Ever wondered how apps like Spotify, Netflix, or Slack manage seamless login experiences across devices? Many of them use JWT, or JSON Web Tokens, a compact, stateless method for securely transmitting user identity and session data across services.</p>\n<p>With JWT token authentication, identity information is embedded in a signed token, allowing you to maintain user sessions without server-side storage. This approach is highly scalable and ideal for modern architectures like SPAs, mobile apps, and microservices.</p>\n<p>In this blog, we’ll walk you through what is JWT, why use it, and how to implement JWT authentication using LoginRadius. </p>\n<p>You’ll learn what JWT is, why it’s effective, and how it works in real-world applications. We'll cover both integration methods (IDX and Direct API), generating your signing key, managing sessions, storing the JWT token securely, and applying best practices throughout.</p>\n<p>Whether you're a developer, product manager, or IAM architect, this guide offers a complete foundation for implementing JWT token authentication into your application stack.</p>\n<h2 id=\"what-is-jwt\" style=\"position:relative;\"><a href=\"#what-is-jwt\" aria-label=\"what is jwt permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is JWT?</h2>\n<p><a href=\"https://www.loginradius.com/blog/engineering/jwt/\">JSON Web Token (JWT)</a> is an open standard (RFC 7519) used to transmit information securely between parties as a JSON object. It’s compact, self-contained, and digitally signed, making it a reliable format for authentication and authorization across modern applications.</p>\n<p>A JWT consists of three parts:</p>\n<ol>\n<li><strong>Header –</strong> Contains metadata like the type of token and signing algorithm (e.g., HS256).</li>\n<li><strong>Payload –</strong> Stores the actual data or “claims,” such as user ID, roles, and token expiry.</li>\n<li><strong>Signature –</strong> A cryptographic hash that ensures the token hasn’t been tampered with.</li>\n</ol>\n<p><em>Example of a token structure:</em></p>\n<p>&#x3C;base64Header>.&#x3C;base64Payload>.&#x3C;signature></p>\n<h2 id=\"why-use-jwt\" style=\"position:relative;\"><a href=\"#why-use-jwt\" aria-label=\"why use jwt permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why Use JWT?</h2>\n<ul>\n<li><strong>Stateless Authentication</strong>: No server-side session storage is needed — the token holds all necessary user info. </li>\n<li><strong>Portable</strong>: Works seamlessly across domains, services, and APIs. </li>\n<li><strong>Scalable</strong>: Ideal for microservices, SPAs, mobile apps, and serverless functions. </li>\n<li><strong>Interoperable</strong>: JWTs are supported across many languages and frameworks.</li>\n</ul>\n<h2 id=\"how-jwt-works\" style=\"position:relative;\"><a href=\"#how-jwt-works\" aria-label=\"how jwt works permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How JWT Works?</h2>\n<p><img src=\"/f29edbf2978577390c7ffa02e9bc4dda/lr-JWT-authentication.webp\" alt=\"Flowchart illustrating LoginRadius JWT authentication via Identity Provider (IDP), showing user redirection from login icon to login page, authentication with IDP, JWT token validation, and subsequent redirection to the customer&#x27;s website or error page based on validation results.\"></p>\n<ol>\n<li>A user logs in with credentials. </li>\n<li>Your app (or identity provider like LoginRadius) issues a signed JWT. </li>\n<li>The client stores the token and sends it with each request (usually in the Authorization header). </li>\n<li>The server validates the token’s signature and claims. </li>\n<li>If valid, access is granted — without any session stored on the backend.</li>\n</ol>\n<p>JWT simplifies identity verification, especially when you're building apps that talk to APIs or need to scale without centralized session storage.</p>\n<h2 id=\"jwt-authentication-with-loginradius-overview\" style=\"position:relative;\"><a href=\"#jwt-authentication-with-loginradius-overview\" aria-label=\"jwt authentication with loginradius overview permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>JWT Authentication with LoginRadius: Overview</h2>\n<p>LoginRadius provides robust support for JWT (JSON Web Token) authentication, which allows for flexible and secure access control across different digital platforms. Whether you're building a fully custom identity flow or using a pre-built interface, the platform supports various integration approaches depending on your architecture.</p>\n<p>If you're looking to understand how to implement JWT token authentication effectively, LoginRadius offers two primary implementation models that cater to different levels of customization and control:</p>\n<h3 id=\"1-idx-implementation--jwt-through-a-hosted-login-page\" style=\"position:relative;\"><a href=\"#1-idx-implementation--jwt-through-a-hosted-login-page\" aria-label=\"1 idx implementation  jwt through a hosted login page permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>1. IDX Implementation – JWT through a Hosted Login Page</h3>\n<p>The IDX-hosted login approach enables secure, standards-compliant, JWT-based authentication without requiring you to build a custom login interface. This is a strategic option for fast, compliant, and user-friendly deployments.</p>\n<ul>\n<li>The Identity Experience Framework (IDX) comes with a fully custom branded hosted login page.</li>\n<li>Once the user logs in and gets enrolled, the user’s JWTs are automatically generated and issued. These tokens can be utilized for managing user sessions and accessing the APIs.</li>\n<li>This approach simplifies deployment without compromising on user experience and security standards.</li>\n</ul>\n<h3 id=\"configuration-steps\" style=\"position:relative;\"><a href=\"#configuration-steps\" aria-label=\"configuration steps permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Configuration Steps:</strong></h3>\n<ol>\n<li>Enable JWT Login</li>\n<li>Go to <a href=\"https://console.loginradius.com/authentication/authentication-configuration\">authentication configuration settings</a> and enable JWT Login in the Admin Console.</li>\n</ol>\n<p><img src=\"/9fb19dd9c88c7916aeebd03ab6e661b7/lr-admin-console.webp\" alt=\"Screenshot of LoginRadius Admin Console showing JWT Custom IDP configuration interface with options for provider name, algorithm (HS256), key entry, clock skew, and expiration time settings.\"></p>\n<ol start=\"2\">\n<li>Specify your signing algorithm and expiry policy, and define your JWT Secret Key.</li>\n<li>Input a secure JWT signing key.</li>\n<li>Specify token expiry duration (e.g., 15–60 minutes)</li>\n<li>Select the desired algorithm —HS256 for symmetric signing (same key signs and verifies)</li>\n<li>RS256 for asymmetric signing, where LoginRadius securely stores the private key used to sign the JWT.</li>\n<li>Your app or backend service uses the public key to validate the token signature.</li>\n<li>LoginRadius provides a JWKS (JSON Web Key Set) endpoint to dynamically fetch and rotate public keys, ensuring trust without key exposure.</li>\n<li>Update IDX Template for Callback</li>\n<li>Modify your IDX login page template to retrieve the JWT post-login. You can access the token via redirect URL parameters or secure JavaScript callbacks.</li>\n</ol>\n<h3 id=\"example-response\" style=\"position:relative;\"><a href=\"#example-response\" aria-label=\"example response permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Example Response:</h3>\n<p>{</p>\n<p>  \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR...\",</p>\n<p>  \"expires_in\": 1800</p>\n<p>}</p>\n<p>This integration approach works best for all teams that want effective identity workflows without the complexity of building proprietary login screens, something that is crucial for customer portals, onboarding of mobile applications, and even managing access for business partners.</p>\n<h3 id=\"2-direct-api-implementation--self-managed-login\" style=\"position:relative;\"><a href=\"#2-direct-api-implementation--self-managed-login\" aria-label=\"2 direct api implementation  self managed login permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>2. Direct API Implementation – Self Managed Login</h3>\n<p>If you’re building a custom login UI or working in a headless environment, LoginRadius lets you generate and handle JWTs directly through its <a href=\"https://www.loginradius.com/docs/api/v2/customer-identity-api/\">Authentication APIs</a>. Here’s how you can programmatically perform token authentication using the classic method:</p>\n<ul>\n<li>For custom front-end applications, LR offers an API to authenticate users and issue JWT tokens.</li>\n<li>In response to the login request, the developers are provided with signed tokens that can be validated on the client’s side or by downstream services.</li>\n<li>This method is best fit for enterprise applications that have complex custom workflows or are designed to be embedded into other applications.</li>\n</ul>\n<h3 id=\"configuration-steps-1\" style=\"position:relative;\"><a href=\"#configuration-steps-1\" aria-label=\"configuration steps 1 permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Configuration Steps:</strong></h3>\n<h4 id=\"step-1-authenticate-via-api\" style=\"position:relative;\"><a href=\"#step-1-authenticate-via-api\" aria-label=\"step 1 authenticate via api permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 1: Authenticate via API:</h4>\n<ul>\n<li>\n<p>Send a POST login request to the LR Authentication URL: </p>\n<p>POST /identity/v2/auth/login</p>\n</li>\n</ul>\n<p>Include the user’s credentials (email + password) in the request body.</p>\n<h4 id=\"step-2-get-jwt-in-response\" style=\"position:relative;\"><a href=\"#step-2-get-jwt-in-response\" aria-label=\"step 2 get jwt in response permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 2: Get JWT in Response</h4>\n<ul>\n<li>If the user credentials are authentic, then the JWT token will be available in response.</li>\n</ul>\n<p>{</p>\n<p> \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",</p>\n<p> \"expires_in\": 3600</p>\n<p>}</p>\n<h4 id=\"step-3-jwt-decoding-and-validation\" style=\"position:relative;\"><a href=\"#step-3-jwt-decoding-and-validation\" aria-label=\"step 3 jwt decoding and validation permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 3: JWT Decoding and Validation</h4>\n<ul>\n<li>Use any JWT library (e.g., jsonwebtoken for Node.js or pyjwt for Python) to decode the token.</li>\n<li>Validate the signature using your configured secret key.</li>\n<li>Confirm claims like exp, iat, aud, and iss.</li>\n</ul>\n<h4 id=\"step-4-set-custom-claims-optional\" style=\"position:relative;\"><a href=\"#step-4-set-custom-claims-optional\" aria-label=\"step 4 set custom claims optional permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Step 4: Set Custom Claims (Optional)</h4>\n<p>With LoginRadius, it is possible to customize the payload to include user roles and/or any additional metadata. You can set custom JWT claims on the Admin Console.</p>\n<p>With this method, you have complete customization over login flows while using LoginRadius to issue signed JWTs for user session management.</p>\n<p><strong>NOTE-</strong> With either method, LoginRadius ensures that JWTs are securely signed, optionally short-lived, and compatible with standard token validation libraries, making integration seamless for everyone.</p>\n<p>To get started with JWT implementation, you can<a href=\"https://www.loginradius.com/docs/single-sign-on/federated-sso/jwt-login/jwt-implementation-guide/\"> read our complete developer documentation</a>. </p>\n<h2 id=\"hosted-login-vs-direct-api\" style=\"position:relative;\"><a href=\"#hosted-login-vs-direct-api\" aria-label=\"hosted login vs direct api permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Hosted Login vs Direct API</h2>\n<p><img src=\"/15ec02ac98d24a9f1f28e5d0f06b9174/IDX-vs-Direct-API-JWT.webp\" alt=\"Illustration showing IDX vs Direct API JWT flow diagram comparing LoginRadius JWT authentication methods via Hosted Login Page (IDX) and Custom Login UI using Direct API, illustrating user login, JWT issuance, and token return process.\"></p>\n<h2 id=\"what-is-session-management-and-how-it-works-with-jwt\" style=\"position:relative;\"><a href=\"#what-is-session-management-and-how-it-works-with-jwt\" aria-label=\"what is session management and how it works with jwt permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is Session Management and How It Works with JWT</h2>\n<p><a href=\"https://www.loginradius.com/blog/identity/user-session-management/\">Session management </a>is how your app keeps track of a user after they log in so they don’t have to prove who they are with every request.</p>\n<p>In traditional apps, sessions are stored on the server using session IDs. Every time a request comes in, the server checks that session ID to verify the user.</p>\n<p>In modern apps, especially SPAs and APIs, JWTs are used to manage sessions without needing server-side storage; this is called stateless session management. The token itself carries the user’s identity, roles, and expiration details. As long as the token is valid, the user stays logged in.</p>\n<p>Good session management ensures:</p>\n<ul>\n<li>Security against session hijacking</li>\n<li>Fast user validation without hitting a database</li>\n<li>Smooth experiences with token refresh strategies</li>\n</ul>\n<h2 id=\"how-loginradius-handles-session-management-with-jwt\" style=\"position:relative;\"><a href=\"#how-loginradius-handles-session-management-with-jwt\" aria-label=\"how loginradius handles session management with jwt permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How LoginRadius Handles Session Management with JWT:</h2>\n<ol>\n<li>\n<p>User Logs In </p>\n<ul>\n<li>LoginRadius returns an access token (JWT) and, optionally, a refresh token.</li>\n</ul>\n</li>\n<li>\n<p>Client Stores the Token </p>\n<ul>\n<li>Access tokens are stored in memory, sessionStorage, or secure cookies. </li>\n<li>They’re sent on every request via the Authorization: Bearer header. </li>\n</ul>\n</li>\n<li>\n<p>Access Token Expiry </p>\n<ul>\n<li>These tokens are short-lived by design (e.g., 15–30 minutes). </li>\n<li>Once expired, the client can use the refresh token to request a new access token. </li>\n</ul>\n</li>\n<li>\n<p>Token Renewal </p>\n<ul>\n<li>LoginRadius validates the refresh token and issues a new JWT, i.e., no user re-authentication is needed. </li>\n<li>Refresh tokens can be revoked at any time.</li>\n</ul>\n</li>\n<li>Logout and Token Revocation Strategy</li>\n</ol>\n<p>When the user logs out, both the access token and refresh token should be cleared from client storage.</p>\n<ul>\n<li>The refresh token can be explicitly revoked via the LoginRadius API, terminating the ability to renew sessions. </li>\n<li>\n<p>However, access tokens are stateless and cannot be revoked mid-lifecycle unless: </p>\n<ul>\n<li>You maintain a blacklist of token IDs (jti claims) and check them on each request. </li>\n<li>You use short-lived access tokens to limit exposure naturally. </li>\n<li>Or, you rotate your JWT signing key, invalidating all previously issued tokens. </li>\n</ul>\n</li>\n</ul>\n<p>Combining these strategies gives you greater control over token misuse and enables a robust, enterprise-grade logout flow. </p>\n<p><a href=\"https://www.loginradius.com/resource/whitepaper/secure-api-using-oauth2\"><img src=\"/e55ae4bbc8ce62e13f03e46e29ebe7cc/api-economy.webp\" alt=\"illustration showing LoginRadius free downloadable resource named API economy is transforming digitization: how to secure it using oauth 2.0.\"></a></p>\n<h2 id=\"how-to-store-jwt-tokens\" style=\"position:relative;\"><a href=\"#how-to-store-jwt-tokens\" aria-label=\"how to store jwt tokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How to Store JWT Tokens?</h2>\n<p>When you implement JWT-based authentication, the client (browser or mobile app) needs a way to store the access token and, optionally, the refresh token after they are issued by the authentication server. This stored token is then attached to every subsequent request to prove the user's identity.</p>\n<p>Choosing where to store the JWT is a crucial security decision. The most common storage options are:</p>\n<ul>\n<li>localStorage</li>\n<li>sessionStorage</li>\n<li>HTTP-only cookies</li>\n</ul>\n<p>Each option has trade-offs between security, accessibility, and persistence, and the right choice depends on your application's architecture and threat model.</p>\n<h4 id=\"recommended-storage-strategy\" style=\"position:relative;\"><a href=\"#recommended-storage-strategy\" aria-label=\"recommended storage strategy permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Recommended Storage Strategy</h4>\n<ul>\n<li>\n<p>Access Tokens </p>\n<ul>\n<li>For SPAs: store in memory or sessionStorage for short-term access </li>\n<li>If stored in the browser, protect against XSS </li>\n</ul>\n</li>\n<li>\n<p>Refresh Tokens</p>\n<ul>\n<li>Always store the JWT refresh token in HTTP-only secure cookies to prevent JavaScript access. This adds a critical layer of protection against XSS attacks.</li>\n<li>Combine with SameSite=Strict or SameSite=Lax attributes to mitigate CSRF risks and ensure the JWT refresh token is only sent in intended contexts.</li>\n</ul>\n</li>\n</ul>\n<h2 id=\"best-practices-for-storing-jwts\" style=\"position:relative;\"><a href=\"#best-practices-for-storing-jwts\" aria-label=\"best practices for storing jwts permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Best Practices for Storing JWTs</h2>\n<ol>\n<li>Never store sensitive tokens (like refresh tokens) in localStorage or sessionStorage.</li>\n<li>Use Secure and HttpOnly flags with cookies to prevent JavaScript access and ensure transmission only over HTTPS.</li>\n<li>Set the SameSite=Strict or Lax attribute on cookies to protect against CSRF.</li>\n<li>Use short-lived access tokens and rotate refresh tokens regularly.</li>\n<li>Implement CSP (Content Security Policy) to reduce XSS risk.</li>\n<li>Avoid storing any tokens in frontend code (e.g., hardcoded in JS files).</li>\n</ol>\n<h2 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Conclusion</h2>\n<p>JWT authentication with LoginRadius offers a modern, stateless approach to managing sessions across distributed systems. The IDX integration is ideal for rapid deployment, while the Direct API model is best for organizations needing deep customization and integration flexibility.</p>\n<p>With robust token signing, refresh capabilities, and centralized control, LoginRadius provides a future-ready foundation for secure, scalable identity architecture. <a href=\"https://www.loginradius.com/contact-us?utm_source=blog&#x26;utm_medium=web&#x26;utm_campaign=how-to-integrate-jwt\">Contact us</a> to know more about JWT authentication and implementation guide. </p>\n<h2 id=\"faqs\" style=\"position:relative;\"><a href=\"#faqs\" aria-label=\"faqs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>FAQs</h2>\n<h3 id=\"1-what-is-jwt-authentication-used-for\" style=\"position:relative;\"><a href=\"#1-what-is-jwt-authentication-used-for\" aria-label=\"1 what is jwt authentication used for permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>1. What is JWT authentication used for?</h3>\n<p><strong>A:</strong> JWT authentication securely verifies user identities, enabling stateless session management across web, mobile apps, and microservices without server-side session storage.</p>\n<h3 id=\"2-how-does-loginradius-simplify-jwt-integration\" style=\"position:relative;\"><a href=\"#2-how-does-loginradius-simplify-jwt-integration\" aria-label=\"2 how does loginradius simplify jwt integration permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>2. How does LoginRadius simplify JWT integration?</h3>\n<p><strong>A:</strong> LoginRadius simplifies JWT integration by offering hosted <a href=\"https://www.loginradius.com/docs/single-sign-on/federated-sso/jwt-login/jwt-implementation-guide/\">IDX login pages </a>and direct API-based authentication methods, enabling rapid deployment and deep customization.</p>\n<h3 id=\"3-is-jwt-authentication-secure\" style=\"position:relative;\"><a href=\"#3-is-jwt-authentication-secure\" aria-label=\"3 is jwt authentication secure permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>3. Is JWT authentication secure?</h3>\n<p><strong>A:</strong> Yes, JWT authentication is secure when implemented with best practices like short-lived tokens, secure storage methods, signature validation, and refresh token rotation.</p>\n<h3 id=\"4-can-jwt-tokens-be-revoked-with-loginradius\" style=\"position:relative;\"><a href=\"#4-can-jwt-tokens-be-revoked-with-loginradius\" aria-label=\"4 can jwt tokens be revoked with loginradius permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>4. Can JWT tokens be revoked with LoginRadius?</h3>\n<p><strong>A:</strong> Yes, LoginRadius allows<a href=\"https://www.loginradius.com/docs/api/v2/customer-identity-api/refresh-token/revoke-refresh-token/?q=revoke+jwt\"> revocation of JWT</a> refresh tokens explicitly, and supports strategies like short-lived tokens and key rotation to manage token lifecycles securely.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n</style>","frontmatter":{"date":"April 15, 2025","updated_date":null,"description":"Discover JWT (JSON Web Token) authentication, its advantages, and how to integrate it seamlessly using LoginRadius' hosted IDX and Direct API methods for secure, scalable identity management.","title":"JWT Authentication with LoginRadius: Quick Integration Guide","tags":["JWT","JSON Web Token","Authentication","Authorization"],"pinned":null,"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":0.7782101167315175,"src":"/static/4cedb7829f98208cbc6d5a9aea4e983d/58556/how-to-integrate-jwt.webp","srcSet":"/static/4cedb7829f98208cbc6d5a9aea4e983d/61e93/how-to-integrate-jwt.webp 200w,\n/static/4cedb7829f98208cbc6d5a9aea4e983d/1f5c5/how-to-integrate-jwt.webp 400w,\n/static/4cedb7829f98208cbc6d5a9aea4e983d/58556/how-to-integrate-jwt.webp 800w,\n/static/4cedb7829f98208cbc6d5a9aea4e983d/1cc9f/how-to-integrate-jwt.webp 896w","sizes":"(max-width: 800px) 100vw, 800px"}}},"author":{"id":"Kundan Singh","github":null,"avatar":null}}}},"pageContext":{"limit":6,"skip":108,"currentPage":19,"type":"//engineering//","numPages":53,"pinned":"5c425581-f474-5ae9-abe7-cf5342db2aaa"}},"staticQueryHashes":["1171199041","1384082988","2100481360","23180105","528864852"]}