<?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 Gufran Mirza on Medium]]></title>
        <description><![CDATA[Stories by Gufran Mirza on Medium]]></description>
        <link>https://medium.com/@_imGufran?source=rss-33e7a4cfb41d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-vfcG5Y9ZnKwEZx5.jpg</url>
            <title>Stories by Gufran Mirza on Medium</title>
            <link>https://medium.com/@_imGufran?source=rss-33e7a4cfb41d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:52:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_imGufran/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[Why Use CSS in JS, Benefits and Drawbacks]]></title>
            <link>https://medium.com/@_imGufran/why-use-css-in-js-benefits-and-drawbacks-df40ab4ebef9?source=rss-33e7a4cfb41d------2</link>
            <guid isPermaLink="false">https://medium.com/p/df40ab4ebef9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css-in-js]]></category>
            <dc:creator><![CDATA[Gufran Mirza]]></dc:creator>
            <pubDate>Thu, 21 Feb 2019 17:29:29 GMT</pubDate>
            <atom:updated>2019-02-21T17:29:29.359Z</atom:updated>
            <content:encoded><![CDATA[<h4>What are the upsides and downsides of these libraries? Is it worth making the switch from separate CSS files?</h4><h3>Why (not) use CSS-in-JS?</h3><p>A lot of big names in the React world are talking about CSS-in-JS. And honestly, it is easy to understand why. Good-ol’ CSS has its fair share of problems, so you’d expect that a lot of smart people would be looking for solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRD1rL2eDui7gYmWWe4o9w.png" /></figure><p>But even if people are making progress towards a better way, I’m not convinced we’re there yet.</p><p>Which isn’t to say that CSS-in-JS doesn’t have its good parts. It does. But it also has some downright ugly parts, while more mature tools solve the same problems without the same downsides.</p><h3>Existing tools work.</h3><p>Most of the problems that CSS-in-JS solves can easily be fixed with more mature tooling like CSS Modules and Webpack. And if you’re considering using CSS-in-JS, these fixes are effectively free, because you’ll need Webpack anyway to put your CSS back into actual CSS files.</p><p>So here is my handy-dandy list of problems that you could have solved without using CSS-in-JS.</p><h3>Eliminating globals</h3><p>Let’s get this one out of the way first, because it is always the first thing that comes up in any list of reasons not to use CSS.</p><p>Yes, everything in CSS is a global:</p><pre>.active {<br>    background: red;<br>}</pre><pre>/* ... lines and lines of unrelated code ... */</pre><pre>.active {<br>    /* oops */<br>    background: blue;<br>}</pre><p>Luckily, there is an outstanding and mature solution to eliminating globals available: <a href="https://github.com/css-modules/css-modules">CSS modules</a>. This comes bundled with Webpack’s CSS loader, so you can already use it, without doing anything.</p><p>But if you don’t want to use Webpack, there is an even simpler solution: use namespaces. And you don’t even need to use complicated namespacing techniques like <a href="http://getbem.com/">BEM</a>. Personally, I namespace classes based on the filesystem path and the name of the component they’re used in:</p><pre>/* An `active` style for a `NavItem` component in the `app` directory */<br>.app-NavItem-active {<br>    background: red;<br>}</pre><pre>/* ... lines and lines of unrelated code ... */</pre><pre>.app-ContactForm-active {<br>    background: blue;<br>}</pre><p>While this may look long-winded, if you’re using SCSS or LESS then the context selector with a dash &amp;- makes things much simper:</p><pre>.app-ContactForm {<br>  &amp;-active {<br>    background: blue;<br>  }</pre><pre>  &amp;-saving, &amp;-fetching {<br>    /* style goes here */<br>  }<br>}</pre><p>Of course, writing these long class names out in your JSX files can be a little painful. But there are tools to generate namespaced class names for you.</p><p>But then again, sometimes you <em>want</em> global styles, like this:</p><pre>@import url(https://medium.com/&#39;http://fonts.googleapis.com/css?family=Roboto:300,400&#39;);</pre><p>Or this:</p><pre>html, body {<br>  position: relative;<br>  height: 100%;<br>  min-height: 100%;<br>  font-family: Roboto;<br>}</pre><p>So whether you use CSS-in-JS or not, you’re still going to need to resort to standard CSS at least some of the time.</p><h3>Style dependencies</h3><p>CSS-in-JS makes it simple to include styles with components. And this is actually a huge benefit. Nobody likes maintaining entirely separate file trees just for their CSS, or managing CSS files which live in completely separate locations to their corresponding JSX.</p><p>But now that we all have access to wonderful tools like Webpack and create-react-app, this benefit isn’t limited to CSS-in-JS. In fact, I place my LESS files right next to my JSX (or JS with Angular), and then include them like this:</p><pre>import &#39;./DocumentForm.less&#39;</pre><p>As for managing dependencies between LESS files? There are a number of ways to do this. CSS Modules is the heavy duty option, but I prefer something much simpler:</p><pre>@import (reference) &#39;~my-less-util/cards.less&#39;;</pre><p>That little (reference) ensures that no output is generated by the @import; it is just a way of importing variables and mixins. This allows each component’s CSS to be completely independent of the other components.</p><h3>Composition of styles</h3><p>Being able to compose classes to create larger, more specific classes is a powerful tool. Luckily, LESS and SCSS have been able to do this for what, maybe a decade? But if this is the case, why do people still act like composition with CSS is difficult?</p><p>The problem isn’t that the technology is lacking. The problem is that designing composable styles is bloody difficult. And as somebody who works with React, you’re probably intimately familiar with the difficulties of decomposing something into smaller, re-usable parts.</p><p>Trying to solve CSS composition with JavaScript is like trying to improve your social life with Facebook. It might make a difference, but only because it gives you a reason to actually try.</p><p><em>If you do want to learn more about designing composable styles, I recommend the excellent article by Adam Wathan, </em><a href="https://adamwathan.me/css-utility-classes-and-separation-of-concerns/"><em>CSS Utility Classes and “Separation of Concerns”</em></a><em>.</em></p><h3>More Power</h3><p>So this is a valid point. You do get more power with CSS-in-JS than you would from CSS or existing tools like LESS, SCSS or PostCSS. But do you really need it?</p><p>No website is complete without a terrible car analogy, so here I go: CSS is a moped. It sucks, but it is what you start out with. It is dangerous, slow, and it quickly teaches you why you need more power. LESS/SCSS is a Japanese car. It is reliable, it gets you where you need to go, it won’t need fixing any time soon, and it’ll still hit the speed limit if you want it to. CSS-in-JS is a sports car — it is damn good at one or two things, but it’ll spend a lot of time in the shop.</p><h3>Drawbacks</h3><p>If all CSS-in-JS did was provide new solutions to old problems, it’d actually be kind of interesting. Of course, like any new technology, it introduces its own problems too.</p><h3>Security?!</h3><p>When researching CSS-in-JS, this made me jump a little. From the <a href="https://www.styled-components.com/docs/advanced#security">styled-components documentation</a>:</p><p>IE sometimes allows JavaScript to be embedded within CSS. This means that if you accidentally interpolate unfiltered user input into a stylesheet, you’re in all sorts of trouble.</p><blockquote><em>Since styled-components allows you to use arbitrary input as interpolations, you must be careful to sanitize that input.</em></blockquote><p>Yep. So not only do you need to remember to sanitize all your inputs, <strong>you need to make your designers do too</strong>. And then trust them to keep doing it. Otherwise you’ll open up your site or app to a fun array of XSS attacks and possibly even arbitrary JavaScript execution.</p><p>This is <em>terrifying</em>.</p><p>To be clear, this won’t be a problem unless you connect user input up to your styles. But will everybody on your team understand how important it is that you <em>never</em> allow stylesheet variables to be set by users?</p><p>A lot of people see the ability to use standard JavaScript variables in styles as a plus. But given the security implications, I’d say that missing out on shared variables is a blessing in disguise.</p><p><em>Read more about the security implication at my answer to </em><a href="https://reactarmory.com/answers/how-can-i-use-css-in-js-securely"><em>How to use CSS-in-JS securely?</em></a><em>.</em></p><h3>Goodbye tooling</h3><p>One of the things about most tooling for styling is that it expects the styles to be in stylesheet files. It may go without saying, but with CSS-in-JS, your styles are <em>not</em> in sylesheet files (at least during development).</p><p>This means that nothing will work. Or more specifically:</p><ul><li>Syntax highlighting will not work, at least without <a href="https://github.com/styled-components/styled-components#syntax-highlighting">some effort</a>. And in some editors.</li><li>Linters will mostly <a href="https://github.com/styled-components/styled-components#linting">not work</a>.</li><li>Hot reloading styles will not work.</li><li>You can’t use LESS, SCSS or PostCSS — or any of your existing mixins.</li></ul><p>And the best part? If you don’t want to use <a href="http://hitchhikers.wikia.com/wiki/Vogon_poetry">vogon poetry</a> as class names during development, you’ll need to setup a <a href="https://github.com/styled-components/babel-plugin-styled-components#better-debugging">babel plugin</a>. Which will take you from classes that look like asdf123, to classes that look like sc-Button-asdf123 asdf123. So your development console is going to look like a mess.</p><h3>Which style wins?</h3><p>So you know how individual styles have priorities?</p><p>Element selectors have the lowest priority — you can override them with CSS classes. Which can be overriden with more classes. And classes can be overridden with IDs, which can in turn be overridden with !important.</p><p><em>Where do CSS-in-JS styles go?</em></p><p>That’s a great question! This will probably depend on the actual library, but at least with styled-components, they <a href="https://www.styled-components.com/docs/advanced#issues-with-specificity">override all selectors</a> that are made with a single class. So if you have this component:</p><pre>&lt;style&gt;<br>.red-background {<br>  background-color: red;<br>}<br>&lt;/style&gt;<br>&lt;SomeStyledComponent className=&quot;red-background&quot;&gt;</pre><pre>&lt;/SomeStyledComponent&gt;</pre><p>The <em>actual</em> background color may well be green. Cool, huh?</p><h3>Designers speak CSS</h3><p>While CSS, LESS and SCSS certainly have their flaws, they have one unbeatable feature: <em>everybody knows them</em>.</p><p>Let’s say you’re building an application with CSS-in-JS, and you want to hire a designer to put together some new pages for you. And for arguments sake, you know a few designers that have a working understanding of React.</p><p>But do they know React and JavaScript well enough to factor out functions where necessary, fix build system issues, and <em>sanitize user inputs securely?</em></p><p>Maybe you do know some people like this — they do exist. But this doesn’t mean you know a designer, it means that you know a <em>frontend god</em>. And good for you. But don’t count on them being around forever.</p><h3>Benifits</h3><p>CSS-in-JS does have a great part: <strong>it isn’t CSS</strong>.</p><p>There are times in a developer’s life where CSS isn’t actually an option. And while this may sound crazy at first, there is actually a relatively common situation where you’ll encounter this requirement:</p><p><strong>You can’t use CSS in react-native apps.</strong> But you <em>can</em> use CSS-in-JS with <a href="https://www.styled-components.com/">styled-components</a>.</p><p>So for all my ranting about CSS-in-JS, I don’t think it is a terrible technology. In fact, I think it is actually pretty cool.</p><p>some other features listed below:</p><ul><li>Live editing and near instant preview of the code changes (using a web worker and the buble transpiler!)</li><li>Service worker integration for better offline support</li><li>A <em>rudimentary</em> file system! Add a file, and import it in the main index file!</li><li>Persistence! Update any file (or add additional files) and you can share that URL with your friends</li><li>Theming by way of a light/dark theme</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df40ab4ebef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React lazy, Suspense and Concurrent React with Examples]]></title>
            <link>https://medium.com/@_imGufran/understanding-react-lazy-suspense-and-concurrent-react-with-examples-b73442956ec2?source=rss-33e7a4cfb41d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73442956ec2</guid>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[suspence]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gufran Mirza]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 08:46:22 GMT</pubDate>
            <atom:updated>2019-02-28T23:54:55.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JW_XVGPTpOVLIawxy6vBVw.jpeg" /></figure><p>There are some major new features and enhancements coming up for the React framework; exciting for us developers, rewarding for the end user. In this article we will be exploring the usage of lazy() and &lt;Suspense /&gt;, but for these features to be fully beneficial we also need to understand concurrent React and the benefits of its support for multi threading.</p><p>Let’s start with what these terms mean:</p><ul><li><strong>Concurrent React:</strong> An update to the underlying React framework that allows it to work on multiple tasks (renders) at the same time. Not only this, these tasks can be switched between according on their priority, on a real-time basis.</li><li><strong>lazy():</strong> lazy is a new API in React to aid in code splitting and importing components into your scripts — very easily.</li><li><strong>&lt;Suspense /&gt;:</strong> Suspense is like an error catcher, which allows us to define fallback JSX if part of the content it is wrapping has not loaded. If you think of a try catch block, the catch block is our Suspence fallback, and everything within &lt;Suspense&gt;&lt;/Suspense&gt; is our try block. This example feels a bit contrived as catch blocks should generally not execute business logic, but the underlying process is very similar.</li></ul><p>Suspense also lets us define a threshold to hold off showing a spinner in the event a component has not loaded in a certain time period. Think of using apps with a fast internet speed that <em>flash in</em> a spinner for a split second, before the loaded content is displayed. We can prevent this with fallbacks.</p><p>Use the following NPM command to install this version</p><p>for react and react-dom:</p><pre>npm install react@16.8.0<br>npm install react-dom@16.8.0</pre><p>So the great news is that we can jump into playing with concurrent React straight away. Below we will explore how to use concurrent React, and jump into lazy() and &lt;Suspense /&gt; examples.</p><p><strong><em>Note:</em></strong><em> Even though these features — and others announced at React Conf 18 — offer some great new ways to work with React, I would not recommend you jump into the alpha and replace your current codebase just yet. Alpha builds usually contain experimental or incomplete modules, which upon final release, may change in function or API. Instead, duplicate your existing projects for testing the concurrent behaviour of your App.</em></p><h3>React.Lazy</h3><p>As mentioned above, lazy() allows us to perform code splitting within our app and import components very easily.</p><p><strong><em>(Code splitting</em></strong> — The idea of breaking (or splitting) your app into various parts so your entire app does not need to load straight away. You may want to only download the homepage for example, and later on download another part of your app when the user actually visits there. Or, since React is now asynchronous, you may want to load the content <em>right before</em> the user visits there!)</p><p>Let’s say I want to load a &lt;Product /&gt; interface, responsible for displaying a product page. This is not necessary when a user first visits my site, therefore I want to split this away from my main bundle.</p><p>Let’s go ahead and import this component:</p><pre>import React, <strong>{ lazy }</strong> from &#39;react&#39;;</pre><pre>const Product = lazy(() =&gt; import(&#39;./ProductHandler&#39;));</pre><p>lazy is imported from the standard React library. It is just a function. We also pass a function into lazy() as its only argument. This function must return a dynamic import, which returns a Promise to a component containing the React component we want to load <em>(which needs to be the default export of the module)</em>.</p><p>This is pretty minimised code, and is not a big departure from what we are used to if we simply import a component without code-splitting capabilities:</p><pre>import { Product } from &#39;./ProductHandler&#39;;</pre><p><strong><em>Note:</em></strong><em> Standard import statement with no code-splitting!</em></p><h3>React.Suspense</h3><p>Now we have a simple API for importing components via code splitting, we need a way to display them if they are fully loaded — and display a placeholder if they are not. This is where &lt;Suspense /&gt; comes into play.</p><p>Implementing Suspense is also straight forward, and does not require a big change to your JSX markup.</p><p>Import Suspense from the standard React package library with the following import statement:</p><pre>import React, { lazy, Suspense } from &#39;react&#39;;</pre><p>To implement Suspense, wrap your JSX (with your lazily loaded imported component within it), with the &lt;Suspense&gt; object:</p><pre>...</pre><pre>render() {</pre><pre>return(<br> &lt;div className=&#39;product-list&#39;&gt;<br>    &lt;h1&gt;My Awesome Product&lt;/h1&gt;</pre><pre><strong>    &lt;Suspense fallback={&lt;h2&gt;Product list is loading...&lt;/h2&gt;}&gt;</strong><br>      &lt;p&gt;Take a look at my product:&lt;/p&gt;<br>      &lt;section&gt; <br>        &lt;Product id=&#39;PDT-49-232&#39; /&gt;<br>      &lt;/section&gt;<br>    <strong>&lt;/Suspense&gt;</strong><br>  &lt;/div&gt;</pre><pre> );<br>}</pre><p>Here, we have wrapped our lazily loaded &lt;Product /&gt; within &lt;Suspense&gt;.</p><p>Suspense’s fallback prop allows us to pass a component (or any JSX markup) into Suspense to display our loading state. In the example above I have just used a &lt;h2&gt; subheading, but feel free to use your a spinner.</p><p>I have deliberately placed some other JSX markup within Suspense to demonstrate that Suspense does not need to be the direct parent object of our lazily loaded components.</p><p>This is also advantageous to us as we may not want to display the “<em>Take a look at my product:</em>” text before &lt;Product /&gt; has loaded. Furthermore, &lt;section&gt; provides additional padding and styling that would look odd in an unloaded product state.</p><p>If my component has not loaded, Suspense works from that component, up the component tree until a Suspense object is found.</p><p>What we can also set up is a scenario where Suspense is waiting for mutliple lazily loaded components to resolve:</p><pre>...</pre><pre>render() {</pre><pre>return(<br> &lt;div className=&#39;product-list&#39;&gt;<br>     &lt;h1&gt;My Awesome Product&lt;/h1&gt;<br>     &lt;Suspense fallback={&lt;h2&gt;Product list is loading...&lt;/h2&gt;}&gt;<br>        &lt;p&gt;Take a look at my product:&lt;/p&gt;<br>        &lt;section&gt; <br>           <strong>&lt;Product id=&#39;PDT-49-232&#39; /&gt;<br>           &lt;Product id=&#39;PDT-50-233&#39; /&gt;<br>           &lt;Product id=&#39;PDT-51-234&#39; /&gt;</strong><br>        &lt;/section&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>In this scenario, all my products need to load before Suspense moves from the fallback to my loaded content.</p><p>What is not well documented online is Error Boundaries. What are Error Boundaries?</p><blockquote>Error Boundaries allow us to catch errors from anywhere in their component tree, log the error, and display fallback UI. We define ErrorBoundaries as a separate class component, define the magic methods <em>getDerivedStateFromError</em>, <em>componentDidCatch</em> and <em>render</em>, and simply import the component and include it in our render method.</blockquote><p>In the case dynamic imports fail to load, Error Boundaries come in handy to display a more friendly UI (more-so than a never ending spinner). An Error Boundary could catch the network error triggered when the module fails to load, which in turn can render a UI that notifies the end user, and could provide a button to reload the resource (or trigger an automatic reload).</p><p>More information on Error Boundaries can be found on reactjs.org:</p><p>What we talked about above can be implemented in synchronous React, but what if we wanted to take advantage of the asynchronous capabilities of concurrent React?</p><h3>Concurrent React</h3><p>We change the way we render our root &lt;App /&gt; element.</p><p>Where we do this in standard React:</p><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><p>We do this for concurrent React:</p><pre>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;App /&gt;<br>);</pre><p>That is all that needs to be changed to enable Concurrent React.</p><p>To continue the talk about Suspense, one of the things it can do in the Concurrent environment is support loading spinner thresholds.</p><p>There is more to the story of Suspense. As mentioned above, we can also define a fallback to prevent the loading state displaying, in the event of a fast internet speed. Just include the &lt;Suspense /&gt; maxDuration prop, which takes a millisecond value.</p><p>Again, don’t expect this to work in non-concurrent React.</p><h3>Enable Strict Mode</h3><p>If you are developing in React 16.6, what has been recommended is to wrap &lt;React.StrictMode&gt; around &lt;App /&gt; so any unsupported features you may integrate will be prompted as warnings in your development console.</p><p>Wrap strict mode around your app like so:</p><pre>ReactDOM.render(<br>  &lt;React.StrictMode&gt;<br>   &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;, document.getElementById(&#39;root&#39;)<br>);</pre><p>Suspense’s maxDuration threshold is just one advantage of using Concurrent React.</p><p>Concurrent React promises to be high performance and deliver smooth UX, which primarily entails less transitions when loading or fetching content. All this functionality is <strong>opt-in,</strong> meaning developers do not have to adopt any of it, and adopting it will not break your current codebase.</p><p>With lazy() and &lt;Suspense /&gt;, we are only scratching the surface of what will materialise from an asynchronous React framework — we can certainly expect big changes to packages, apps and user experiences in the coming months.</p><p>The React core devs are also working on experimental packages such as react-cache, which has the ability to cache imported and fetched data, and therefore have no need to request it again upon every page visit or refresh. This is not available for public testing at this time, but may be another valuable tool for additional UI simplicity for the end user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73442956ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full Stack Error Handling with GraphQL and Apollo]]></title>
            <link>https://medium.com/@_imGufran/full-stack-error-handling-with-graphql-and-apollo-4f1c0b61897b?source=rss-33e7a4cfb41d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f1c0b61897b</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo]]></category>
            <dc:creator><![CDATA[Gufran Mirza]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 18:49:41 GMT</pubDate>
            <atom:updated>2019-02-24T23:56:44.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error handling in Apollo Server 2.0</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GjtW09TFx0WF2ylgCTEhjA.png" /></figure><p>One of the new features in Apollo Server 2.0 is the <a href="https://www.apollographql.com/docs/apollo-server/v2/features/errors.html">ability to add error codes</a>to your GraphQL response. Any errors exported by Apollo Server that you throw in your resolver will augment the error response with a human-readable string in the extensions.code field. We are rolling out this feature with a few basic errors:</p><ul><li>AuthenticationError — for authentication failures</li><li>ForbiddenError — for authorization failures</li><li>UserInputError — for validation errors on user input</li><li>As a fallback for uncaught failures, any other unknown errors thrown within your resolver will add the code INTERNAL_SERVER_ERROR</li></ul><h4>Throwing ApolloErrors in your resolvers</h4><p>Imagine you want to prevent unauthenticated users from executing certain queries. In the resolver for the protected action, you can check for the user object in the query context, and throw an AuthenticationError if it is not available.</p><pre>import { AuthenticationError } from &#39;apollo-server&#39;<br>const resolvers = {<br>  Mutation: {<br>    protectedAction(root, args , { user }) { <br>      if (!user) { <br>        throw new AuthenticationError(&#39;You must be logged in&#39;);<br>      }<br>    }<br>  }<br>};</pre><p>This is how the response will look like:</p><pre>{<br>  &quot;error&quot;: {<br>    &quot;graphQLErrors&quot;: [<br>      {<br>        &quot;message&quot;: &quot;forbidden&quot;,<br>        &quot;locations&quot;: [],<br>        &quot;path&quot;: [<br>          &quot;protectedAction&quot;<br>        ],<br>        &quot;extensions&quot;: {<br>          &quot;code&quot;: &quot;UNAUTHENTICATED&quot;,<br>        }<br>      }<br>    ],<br>    &quot;networkError&quot;: null,<br>    &quot;message&quot;: &quot;GraphQL error: You must be logged in&quot;<br>  }<br>}</pre><p>Having well-defined error codes in your error responses lays the groundwork to make GraphQL errors more actionable and universal. The benefits of using them consistently throughout our application stack are pretty compelling:</p><ul><li>Error handlers can read the error codes to distinguish between transient errors (like expired authentication tokens) vs non-transient errors (bad user input), and possibly retry the transient errors automatically.</li><li>Packages and applications can use the standard error codes to build out an error-aware ecosystem of tooling. For example, we can filter out service-level errors that reflect the health of the API, while ignoring errors caused by bad user input.</li></ul><h3>Handling user level errors</h3><p>At this point, hopefully we have done a good job of dealing with most service level errors nicely, and found ways to smooth over its impact on the user experience. However, users can frequently be the source of errors as well.</p><p>Even a well-meaning user or client will not always send data that your GraphQL endpoint expects, so every application needs to validate user input rigorously. In GraphQL, there are two levels of validation errors that could occur:</p><h4>GraphQL Type Validation</h4><p>In GraphQL, we automatically benefit from a strongly typed schema — any time a user types in a string when an int was expected as input, an error is thrown from the validation phase within <a href="https://github.com/graphql/graphql-js">GraphQL-JS</a>. Such errors prevent your GraphQL server from executing the query, resulting in the entire query being rejected. On the client, this shows up as a networkError with a message that looks like this:</p><pre>&quot;message&quot;: &quot;Variable \&quot;$input\&quot; got invalid value \&quot;foo\&quot;; Expected type Int; Int cannot represent non 32-bit signed integer value: foo&quot;\</pre><p>In general, your application should avoid sending bad queries like this to your GraphQL endpoint. First, it wastes unnecessary server resources, and second, it reduces the ability to provide quick feedback to the user on the UI. I suggest that the best way to deal with type errors is to perform strong client-side validation using packages like <a href="https://github.com/chriso/validator.js">this</a>. If your schema is available on the client, you can also run the same <a href="https://github.com/graphql/graphql-js/tree/master/src/validation">validation step</a> GraphQL-JS provides before sending a request.</p><h4>Custom Validation in your resolvers</h4><p>However, validation is surely more than just checking whether the input types match what is expected by the schema — we need to make sure that the inputs are semantically correct. Say you would like to create an app that allows users to post events that are happening in town. The schema for an Event might look something like this.</p><pre>const typeDefs = gql`<br>  type Event {<br>    name: String!<br>    date: Date!<br>    capacity: Int!<br>    zipCode: String!<br>  }<br>`;</pre><p>Notice there are already multiple ways that the user could send invalid inputs. He might enter a date in the past, use a duplicate event name, or enter an invalid URL for the display photo. Checks against these types of mistakes typically require the use of server-side data, and should live in your GraphQL resolvers.</p><h4>Throwing BadUserInputError in resolvers</h4><p>Throwing UserInputError from Apollo Server gives us a really convenient way of adding field-level validation error information to the error response. Notice that the second argument to UserInputError allows you to specify these additional properties to include. A simple example is as follows:</p><pre>import { UserInputError } from &#39;apollo-server&#39;;<br><br>const resolvers = {<br>  Query: {<br>    events(root, { zipCode }) {<br>      <br>      // do custom validation for user inputs<br>      const validationErrors = {};<br>      if (!isValidZipCode(zipCode)) {<br>        validationErrors.zipCode = &#39;This is not a valid zipcode&#39;;<br>      }<br>      if (Object.keys(validationErrors).length &gt; 0) {<br>        throw new UserInputError(<br>          &#39;Failed to get events due to validation errors&#39;,<br>          { validationErrors }<br>        );<br>      }<br>      // actually query events here and return successfully<br>      return getEventsByZipcode(zipCode);<br>    }<br>  }<br>}</pre><p>Failing validation, here is how the response will look on the client:</p><pre>{<br>  &quot;message&quot;: &quot;Failed to get events due to validation errors&quot;,<br>  &quot;extensions&quot;: {<br>    &quot;code&quot;: &quot;BAD_USER_INPUT&quot;,<br>    &quot;exception&quot;: {<br>      &quot;validationErrors&quot;: {<br>        &quot;zipCode&quot;: &quot;This is not a valid zipcode&quot;<br>      }<br>    }<br>  }<br>}</pre><p>While convenient, the weakness of this approach is that the format of the validation error messages is not captured by your schema, making it brittle to changes. Unless you maintain tight control of both server and client, you should keep the error responses as simple as possible.</p><p>For mutations, it can be worthwhile defining these validation errors as first class citizens within your schema. For more, you can look at the <a href="https://www.apollographql.com/docs/guides/schema-design.html#mutation-responses">schema design guides</a>.</p><h3>Handling partial failures with nullable types</h3><p>One of the great things about using GraphQL as your API gateway is the ability to stitch together data from different back-end services, allowing the client to fetch the data it needs with a single query. While this is great if you have a microservice architecture, you’ll also have to think carefully about how to handle partial failures. I strongly recommend <a href="https://medium.com/u/803918030a60">Sashko Stubailo</a>’s excellent post on how to use <a href="https://dev-blog.apollodata.com/using-nullability-in-graphql-2254f84c4ed7">nullability in GraphQL</a>, but here is a takeaway from his discussion as it relates to error handling:</p><p><strong>Use nullable types for fields on which partial failure is acceptable. For critical fields in your query, specify them as non-nullable so the entire query fails when those fields fail to resolve.</strong></p><h3>Conclusion</h3><p>Hopefully this blog post has given you some ideas on how to handle the variety of errors that we will encounter when using GraphQL. For easy reference, here is a flowchart that summarizes the thinking process for using each approach that we have discussed in this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f1c0b61897b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>