<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anurag Sinha on Medium]]></title>
        <description><![CDATA[Stories by Anurag Sinha on Medium]]></description>
        <link>https://medium.com/@sinhanurag?source=rss-487162dc84e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZELjJpaNx26t-cYJgAHUdg@2x.jpeg</url>
            <title>Stories by Anurag Sinha on Medium</title>
            <link>https://medium.com/@sinhanurag?source=rss-487162dc84e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:21:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sinhanurag/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Batch: An API to bundle multiple PayPal REST operations]]></title>
            <link>https://medium.com/paypal-tech/batch-an-api-to-bundle-multiple-paypal-rest-operations-6af6006e002?source=rss-487162dc84e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6af6006e002</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[ecommerce-platform]]></category>
            <dc:creator><![CDATA[Anurag Sinha]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 18:54:54 GMT</pubDate>
            <atom:updated>2018-12-06T16:05:24.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAaLjtxEjqtoSNXAh1sxTQ.jpeg" /></figure><h3>Batch: An API to bundle multiple REST operations</h3><p><a href="https://developer.paypal.com/docs/api/overview">REST APIs </a>are vital business tools that allow merchants, partners and developers to consume and build on top of the various payment capabilities that PayPal provides. Whether it is checkout, recurring payments, vaulting or identity operations there are multiple end to end API interactions involved in each of those business flows.</p><p>These APIs are also a critical part of the internal Service Oriented Architecture (SOA) at PayPal. Different domains expose various internal capabilities and operations via REST interfaces using which the PayPal platform orchestrates and processes billions of transactions per day.</p><p>Earlier this year, <a href="https://www.linkedin.com/in/aniket-pol/">Aniket Pol</a> and I started working on a project that would allow for logical bundling of these different REST API operations into one single API call on an <strong><em>as-needed basis</em></strong>. The primary motivation behind this being; cutting down on the number of API calls between external clients (merchants and developers) and PayPal or between different internal services at PayPal.</p><blockquote>Reducing multiple API calls into a single API call between client and server allows for enormous performance boost as we cut down significantly on the round trip network time.</blockquote><p>Another common business use case is doing bulk API operations. Often large merchants and marketplaces initiate transactions in bulk where they need to create multiple payments at one go.</p><blockquote>There was a need for an interface that allows clients to invoke the same API call with different request contexts multiple times via a single optimized API call. This eliminates the need for the clients to call an API endpoint in bulk and write code at their end to manage parallel and sequential requests.</blockquote><p>Enter <strong><em>Batch API </em></strong>that facilitates the logical bundling of these multiple REST calls via a simplified interface. This REST API is based on the <a href="https://tools.ietf.org/html/rfc7644">IETF SCIM specification</a> which provides guidance on how clients can send a large collection of resource operations in a single request. The body of a bulk operation contains a set of HTTP resource operations using one of the HTTP methods supported by the API such as POST, PUT, PATCH, or DELETE.</p><p>Using this API one can make both <strong>non-dependent</strong> and <strong>dependent</strong> batch requests to the PayPal server.</p><p><strong>Non-dependent batch requests do not support dependencies between batch operations.</strong></p><p>Non-dependent batch requests contain multiple API operations that are not dependent on each other. For example bulk API operations in which one API endpoint is being called multiple times would be a collection of non-dependent operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okfjJcmLRgw0rVkE66xkEw.png" /><figcaption>Processing a non-dependent batch request</figcaption></figure><p>The PayPal batch server returns the response of the batch request as a single-wrapped response only after receiving responses for individual independent operations.</p><p>Here is an example of how a non-dependent batch API request looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHy7IjcoyGLiBYejlS0yiA.png" /></figure><p>Notice how we can define an array of API operations that are independent of each other and send them in one single request. The batch service handles unwrapping them and executing them in an optimized fashion and returns the response.</p><p>The response for a batch operation like this also contains an array of operations with individual response metadata and body for each operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDlJ11u7s21qA2KqzNxpcg.png" /></figure><p><strong>Dependent batch requests support dependencies between two operations.</strong></p><p>Dependent batch requests contain multiple API operations that are dependent on each other. For example, the output of one operation might be passed as input to another operation in the batch request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8x5Ena2nueGqgKNSW94gg.png" /><figcaption>Processing a dependent batch request</figcaption></figure><p>Here is an example of how a dependent batch request looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR2zYWAr0b1W51HN4d7_BA.png" /></figure><p>Notice how the dependency is defined. The resource Id generated as part of the first operation (defined by operation Id<strong> </strong><em>— f81d4fae-7dec-11d0-a765–00a0c91e6bf6</em>) is used as an input to the second dependent operation in the path as <em>v1/payments/payment/{bulk_id:f81d4fae-7dec-11d0-a765–00a0c91e6bf6}</em><strong><em>.</em></strong></p><p>The batch service takes care of orchestrating the first request and then using the resource Id generated as the result of that in the second operation. This is exactly how a client consuming 2 dependent APIs sequentially would make the calls as well.</p><p>Currently this API is in pilot mode and supports the batching of only certain PayPal Checkout API operations being used by some of our large partners and we plan on making it gradually available for widespread use. We see promising performance gains with these integrations.</p><p>Please feel free to drop us a <a href="/service/mailto:DL-PayPal-Batch-API@paypal.com">note</a> in case you would be interested in trying out this API for your integration.</p><p>Huge shout out to our API architects — <a href="https://www.linkedin.com/in/asusarla/">Aruna Susarla</a>, <a href="https://www.linkedin.com/in/jayadeba-jena-1a6a0020/">Jayadeba Jena</a>; product managers — <a href="https://www.linkedin.com/in/adritabhor">Adrita Bhor</a>, <a href="https://www.linkedin.com/in/rahuldighe/">Rahul Dighe</a> and intern <a href="https://www.linkedin.com/in/divya-saxena-05ba4144/">Divya Saxena</a> who helped and guided us on this cross collaborative effort to bring this API to life for our customers.</p><p>We’re hiring if you would like to come work on exciting backend platforms and customer facing APIs drop me a DM at <a href="http://twitter.com/anuragS28">@anuragS28</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6af6006e002" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paypal-tech/batch-an-api-to-bundle-multiple-paypal-rest-operations-6af6006e002">Batch: An API to bundle multiple PayPal REST operations</a> was originally published in <a href="https://medium.com/paypal-tech">The PayPal Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just another Git Cheat Sheet]]></title>
            <link>https://medium.com/@sinhanurag/another-git-cheat-sheet-3b5a123f49e5?source=rss-487162dc84e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b5a123f49e5</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Anurag Sinha]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 04:51:04 GMT</pubDate>
            <atom:updated>2018-01-18T05:25:31.054Z</atom:updated>
            <content:encoded><![CDATA[<h4>A running list of git tips and tricks.</h4><h3>Cherry Picking</h3><p>The <a href="https://git-scm.com/docs/git-cherry-pick">git cherry-pick</a> command is used to pick a single commit or a range of commits (Git 1.7.2+) from one branch and apply it to another branch.</p><p><em>Here is how you can Cherry pick a range of commits from one branch (in a remote) and apply it to another branch (in the same or different remote):</em></p><ol><li>In case not already done add the remote from which the commits have to be cherry-picked and do a fetch to get the commit history.</li></ol><pre>git remote add &lt;remote_name&gt; &lt;url&gt;<br>git fetch &lt;remote_name&gt;</pre><pre>E.g.<br> <br>$ git remote add origin https://github.com/sinhanurag/myrepo</pre><pre>$ git fetch origin</pre><pre>remote: Counting objects: 6, done.<br>remote: Total 6 (delta 0), reused 0 (delta 0), pack-reused 6<br>Unpacking objects: 100% (6/6), done.<br>From https://github.com/sinhanurag/myrepo<br> * [new branch]      develop    -&gt; origin/develop<br> * [new branch]      master     -&gt; origin/master<br> * [new branch]      release    -&gt; origin/release</pre><p>2. Obtain the commits you want to cherry pick from the remote branch.</p><pre>git log &lt;remote_name&gt;/&lt;branch_name&gt;</pre><pre>E.g.</pre><pre>$ git log upstream/master</pre><pre>commit fd7d0d7873461a264 (upstream/master)<br>Author: Author1 &lt;author1@email.com&gt;<br>Date:   Fri Dec 29 10:17:55 2017 +0530</pre><pre>Terminal Commit</pre><pre>commit abba470a466776dbb<br>Author: Author1 &lt;author1@email.com&gt;<br>Date:   Thu Dec 28 18:50:36 2017 +0530</pre><pre>Commit 3</pre><pre>commit 42a9af7f08b36b21<br>Author: Author2 &lt;author2@email.com&gt;<br>Date:   Thu Dec 28 18:12:29 2017 +0530</pre><pre>Commit 2</pre><pre>commit 9beeb2f216d81f1d<br>Author: Author1 &lt;author1@email.com&gt;<br>Date:   Thu Dec 28 17:29:37 2017 +0530</pre><pre>Commit 1</pre><pre>commit 6e30dac520faef4a1<br>Author: Author3 &lt;author3@email.com&gt;<br>Date:   Thu Dec 28 13:35:30 2017 +0530</pre><pre>Initial Commit</pre><p>3. Assuming you want to cherry pick all commits between “Initial commit” . and the “Terminal Commit” use the following syntax. <strong>This will pick each commit between the 2 specified commits (excluding the range commits) and apply them to the current branch in your local.</strong></p><pre>git cherry-pick &lt;initial_commit_hash&gt;..&lt;terminal_commit_hash&gt;</pre><pre>E.g.</pre><pre>$ git cherry-pick 6e30dac520faef4a1..fd7d0d7873461a26</pre><pre>On branch develop<br>You are currently cherry-picking commit d856905.</pre><p>4. If you want to include the range commits the syntax for the cherry picking command is a little different.</p><pre>git cherry-pick &lt;initial_commit_hash&gt;^..&lt;terminal_commit_hash&gt;</pre><p>Please note that as each commit is applied to the current branch in case of any conflicts or a need of resolution git will pause the merging and ask you to resolve the issue for that particular commit.</p><p>You can resume the cherry-picking using the following command.</p><pre>git cherry-pick --continue</pre><p>Here is a list of all possible cherry-pick options</p><pre>$ git cherry-pick<br>usage: git cherry-pick [&lt;options&gt;] &lt;commit-ish&gt;...<br>   or: git cherry-pick &lt;subcommand&gt;</pre><pre>--quit                end revert or cherry-pick sequence<br>    --continue            resume revert or cherry-pick sequence<br>    --abort               cancel revert or cherry-pick sequence<br>    -n, --no-commit       don&#39;t automatically commit<br>    -e, --edit            edit the commit message<br>    -s, --signoff         add Signed-off-by:<br>    -m, --mainline &lt;parent-number&gt;<br>                          select mainline parent<br>    --rerere-autoupdate   update the index with reused conflict resolution if possible<br>    --strategy &lt;strategy&gt;<br>                          merge strategy<br>    -X, --strategy-option &lt;option&gt;<br>                          option for merge strategy<br>    -S, --gpg-sign[=&lt;key-id&gt;]<br>                          GPG sign commit<br>    -x                    append commit name<br>    --ff                  allow fast-forward<br>    --allow-empty         preserve initially empty commits<br>    --allow-empty-message<br>                          allow commits with empty messages<br>    --keep-redundant-commits<br>                          keep redundant, empty commits</pre><h3>Squashing</h3><p>Often there is a need to squash or club multiple commits into one in order to keep your commit history clean. Git allows you to modify the commit history.</p><p><em>Here is how you can use rebase to club last N commits into 1 using interactive rebase:</em></p><pre>git rebase -i &lt;branch_name&gt;</pre><pre>E.g </pre><pre>$ git rebase -i master</pre><pre>pick 5477060 Test commit 1<br>pick a3d6192 Test commit 2<br>pick 67456dg Test commit 3</pre><pre># Rebase b5081cc..a3d6192 onto b5081cc (2 commands)<br>#<br># Commands:<br># p, pick = use commit<br># r, reword = use commit, but edit the commit message<br># e, edit = use commit, but stop for amending<br># s, squash = use commit, but meld into previous commit<br># f, fixup = like &quot;squash&quot;, but discard this commit&#39;s log message<br># x, exec = run command (the rest of the line) using shell<br># d, drop = remove commit<br>#<br># These lines can be re-ordered; they are executed from top to bottom.<br>#<br># If you remove a line here THAT COMMIT WILL BE LOST.<br>#<br># However, if you remove everything, the rebase will be aborted.<br>#<br># Note that empty commits are commented out</pre><p>The interactive prompt is pretty informative in how to go about modifying the commit history (or clubbing the commits). Assuming you want to combine the 2nd commit (Test Commit 1) and 3rd commits (Test commit 3) onto the 1st commit (Test Commit 2) change the command in front of the commits respectively to:</p><pre>p 5477060 Test commit 1<br>s a3d6192 Test commit 2<br>s 67456dg Test commit 3</pre><p>Once you save your changes to the file (wq! in vim) you should get the following prompt specify the commit message on top and save the file</p><pre>SQUASHED COMMIT MESSAGE<br># This is a combination of 3commits.<br># This is the 1st commit message:</pre><pre>Test commit 1</pre><pre># This is the commit message #2:</pre><pre>Test commit 2</pre><pre># This is the commit message #3:</pre><pre>Test commit 3</pre><pre># Please enter the commit message for your changes. Lines starting<br># with &#39;#&#39; will be ignored, and an empty message aborts the commit.<br>#<br># Date:      Wed Jan 17 20:38:07 2018 -0800<br>#<br># interactive rebase in progress; onto b5081cc<br># Last commands done (2 commands done):<br>#    p 5477060 Test commit 1<br>#    s a3d6192 Test commit 2<br>#    s 67456dg Test commit 3<br># No commands remaining.<br># You are currently rebasing branch &#39;master&#39; on &#39;b5081cc&#39;.<br>#<br># Changes to be committed:<br>#       modified:   README.md</pre><p>Voila! you should get a message confirming the successful rebase:</p><pre>[detached HEAD d421532] SQUASHED COMMIT MESSAGE<br> Date: Wed Jan 17 20:38:07 2018 -0800<br> 1 file changed, 2 insertions(+), 2 deletions(-)<br>Successfully rebased and updated refs/heads/master.</pre><p>You can verify the commit history via a git log</p><pre>commit d421532e982f1ee320052cfbaf37b5e43e0aadc0 (HEAD -&gt; master)<br>Author: Author &lt;<a href="/service/mailto:sinhanurag@hotmail.com">author@mail.com</a>&gt;<br>Date:   Wed Jan 17 20:38:07 2018 -0800</pre><pre>SQUASHED COMMIT MESSAGE</pre><pre>Test commit 1</pre><pre>Test commit 2</pre><pre>Test commit 3</pre><p>Please note if you have already pushed to remote you might have to push again with -f flag to force rewrite the commit history on the remote again.</p><p>More to come..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b5a123f49e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.JS Single Page Apps  —  handling cookies disabled mode]]></title>
            <link>https://medium.com/paypal-tech/node-js-single-page-apps-handling-cookies-disabled-mode-df6f3d685a67?source=rss-487162dc84e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/df6f3d685a67</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anurag Sinha]]></dc:creator>
            <pubDate>Wed, 01 Jun 2016 22:58:58 GMT</pubDate>
            <atom:updated>2018-07-09T23:25:33.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node.JS Single Page Apps — handling cookies disabled mode</h3><p><a href="https://tools.ietf.org/html/rfc6265">Cookies</a> since their advent have been an integral part of web applications. Since the underlying web HTTP protocol is stateless, cookies provide a nifty way to carry state full information about the user to the web server. With the rise of the <strong>Single Page Application (SPA)</strong>, cookies have become even more instrumental to provide for a state full front end communicating with a stateless backend. Cookies are commonly used for user authentication, experience customization, tracking users across multiple visits etc.</p><p>All modern browsers today by default enable cookies to be set by the various domains. However there may be cases in which the user could have disabled setting cookies or some HTTP clients such as certain <a href="https://developer.android.com/reference/android/webkit/CookieManager.html#setAcceptCookie%28boolean%29">web-views</a> might not allow cookies by default. In order to make sure that the users who access your website from such clients are still able to get a seamless experience, it becomes imperative to handle the <strong>“Cookies Disabled Mode”</strong>.</p><p>This was one of our major considerations while <a href="https://medium.com/@bluepnume/sane-scalable-angular-apps-are-tricky-but-not-impossible-lessons-learned-from-paypal-checkout-c5320558d4ef#.hwi3d0qs0">re-architecting</a> the Checkout flow at PayPal last year. How did we solve it? <a href="https://github.com/krakenjs/memcookies">Memcookies</a>!</p><p>Let’s break down the problem statement into its constituents:</p><ol><li>We need an alternative to the browser’s cookie jar to persist the cookies in the front end.</li><li>We need a mechanism to send these cookies as part of every AJAX request to the server and to ensure that the new cookies being set in the response are again persisted in the alternative storage (mentioned in 1 above).</li></ol><p>For the first one since our app is a JavaScript powered heavy weight SPA the ideal location for the persisted cookies is in the Front End JS context. Hence we wrote a client side JS script that took care of persisting the cookies onto the front-end.</p><p>For the second, the client side JS uses a custom HTTP header to send across all the cookies as part of every AJAX request from the client. We ended up writing a Node.JS middleware that intercepts every incoming request, reads the custom header, extracts all the cookies and populates them in the Cookies header for downstream middleware to consume.</p><p>For setting the response cookies the middleware again fires whenever the response headers are being <a href="https://www.npmjs.com/package/on-headers">sent</a> and it reads all <em>Set-Cookie </em>headers, extracts the cookie name-values and populates it in the custom HTTP header that out client side script understands.</p><p>Note that this approach has certain limitations though:</p><ol><li>This approach works only for AJAX requests and not full page POST since it relies on being sent through custom HTTP headers, and being persisted in memory on a single page.</li><li>Using the existing <em>cookie</em> header is off limits. It is not possible to set this header for AJAX requests, nor is it possible to read cookies for a response when they are set as <em>HttpOnly</em>. As such, we use a <em>x</em>-<em>cookies</em> header instead.</li><li>We do not want javascript to have free reign over these cookies, given that most of them are designed to be <em>HttpOnly</em>. Hence, we encrypt all cookies on the way out, and decrypt them on the way back in. So cookies are now transparently handled on the front-end.</li><li>We rely on the front-end to tell us when it’s in cookies disabled mode.</li><li>For the initial page render, we provide <em>res._cookies</em> for the renderer to drop on the page. The alternative is making an additional AJAX request, in order to get the <em>x</em>-<em>cookies</em> object in headers.</li><li>Since the browser can no longer expire cookies on outgoing responses, we can instead do this on incoming requests, by encoding the expiry time into the encrypted cookie value. Also, we can set a hard ceiling on this expiry time of 20 minutes, given that the cookies are only intended to exist until the user is redirected from the page.</li></ol><p>Using this approach of persisting cookies in client side JS context and sending them to the backend server via HTTP headers has scaled pretty well for us. This middleware can ideally be used as a supplement prior to any cookie parser <a href="https://github.com/expressjs/cookie-parser">middleware</a> so as to enable reading and setting cookies by the app even for cookie disabled browsers.</p><p>Credits to <a href="https://medium.com/u/97f5eca783db">Daniel Brain</a> who is the original author of memcookies.</p><p>You can checkout the memcookies middleware and the bundled client side JS along with their usage in the above linked repo. Pull Requests/Issues are welcome for suggestions and (or) improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df6f3d685a67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paypal-tech/node-js-single-page-apps-handling-cookies-disabled-mode-df6f3d685a67">Node.JS Single Page Apps  —  handling cookies disabled mode</a> was originally published in <a href="https://medium.com/paypal-tech">The PayPal Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.JS Single Page Apps — handling cookies disabled mode.#krakenjs]]></title>
            <link>https://medium.com/front-end-weekly/node-js-single-page-apps-handling-cookies-disabled-mode-f6c21debae35?source=rss-487162dc84e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6c21debae35</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[krakenjs]]></category>
            <dc:creator><![CDATA[Anurag Sinha]]></dc:creator>
            <pubDate>Wed, 01 Jun 2016 04:29:26 GMT</pubDate>
            <atom:updated>2017-07-30T00:52:40.657Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://tools.ietf.org/html/rfc6265">Cookies</a> since their advent have been an integral part of web applications. Since the underlying web HTTP protocol is stateless, cookies provide a nifty way to carry state full information about the user to the web server. With the rise of the <strong>Single Page Application (SPA)</strong>, cookies have become even more instrumental to provide for a state full front end communicating with a stateless backend. Cookies are commonly used for user authentication, experience customization, tracking users across multiple visits etc.</p><p>All modern browsers today by default enable cookies to be set by the various domains. However there may be cases in which the user could have disabled setting cookies or some HTTP clients such as certain <a href="https://developer.android.com/reference/android/webkit/CookieManager.html#setAcceptCookie(boolean)">web-views</a> might not allow cookies by default. In order to make sure that the users who access your website from such clients are still able to get a seamless experience, it becomes imperative to handle the <strong>“Cookies Disabled Mode”</strong>.</p><p>This was one of our major considerations while <a href="https://medium.com/@bluepnume/sane-scalable-angular-apps-are-tricky-but-not-impossible-lessons-learned-from-paypal-checkout-c5320558d4ef#.hwi3d0qs0">re-architecting</a> the Checkout flow at PayPal last year. How did we solve it? Memcookies!</p><p><a href="https://github.com/krakenjs/memcookies">krakenjs/memcookies</a></p><p>Let’s break down the problem statement into its constituents:</p><ol><li>We need an alternative to the browser’s cookie jar to persist the cookies in the front end.</li><li>We need a mechanism to send these cookies as part of every AJAX request to the server and to ensure that the new cookies being set in the response are again persisted in the alternative storage (mentioned in 1 above).</li></ol><p>For the first one since our app is a JavaScript powered heavy weight SPA the ideal location for the persisted cookies is in the Front End JS context. Hence we wrote a client side JS script that took care of persisting the cookies onto the front-end.</p><p>For the second, the client side JS uses a custom HTTP header to send across all the cookies as part of every AJAX request from the client. We ended up writing a Node.JS middleware that intercepts every incoming request, reads the custom header, extracts all the cookies and populates them in the Cookies header for downstream middleware to consume.</p><p>For setting the response cookies the middleware again fires whenever the response headers are being <a href="https://www.npmjs.com/package/on-headers">sent</a> and it reads all <em>Set-Cookie </em>headers, extracts the cookie name-values and populates it in the custom HTTP header that out client side script understands.</p><p>Note that this approach has certain limitations though:</p><ol><li>This approach works only for AJAX requests and not full page POST since it relies on being sent through custom HTTP headers, and being persisted in memory on a single page.</li><li>Using the existing <em>cookie</em> header is off limits. It is not possible to set this header for AJAX requests, nor is it possible to read cookies for a response when they are set as <em>HttpOnly</em>. As such, we use a <em>x</em>-<em>cookies</em> header instead.</li><li>We do not want javascript to have free reign over these cookies, given that most of them are designed to be <em>HttpOnly</em>. Hence, we encrypt all cookies on the way out, and decrypt them on the way back in. So cookies are now transparently handled on the front-end.</li><li>We rely on the front-end to tell us when it’s in cookies disabled mode.</li><li>For the initial page render, we provide <em>res._cookies</em> for the renderer to drop on the page. The alternative is making an additional AJAX request, in order to get the <em>x</em>-<em>cookies</em> object in headers.</li><li>Since the browser can no longer expire cookies on outgoing responses, we can instead do this on incoming requests, by encoding the expiry time into the encrypted cookie value. Also, we can set a hard ceiling on this expiry time of 20 minutes, given that the cookies are only intended to exist until the user is redirected from the page.</li></ol><p>Using this approach of persisting cookies in client side JS context and sending them to the backend server via HTTP headers has scaled pretty well for us. This middleware can ideally be used as a supplement prior to any cookie parser <a href="https://github.com/expressjs/cookie-parser">middleware</a> so as to enable reading and setting cookies by the app even for cookie disabled browsers.</p><p>Credits to <a href="https://medium.com/u/97f5eca783db">Daniel Brain</a> who is the original author of memcookies.</p><p>You can checkout the memcookies middleware and the bundled client side JS along with their usage in the above linked repo. Pull Requests/Issues are welcome for suggestions and (or) improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6c21debae35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/node-js-single-page-apps-handling-cookies-disabled-mode-f6c21debae35">Node.JS Single Page Apps — handling cookies disabled mode.#krakenjs</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>