<?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 Gergő Mészáros on Medium]]></title>
        <description><![CDATA[Stories by Gergő Mészáros on Medium]]></description>
        <link>https://medium.com/@gergmszros?source=rss-934df357ec29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*byTt18c3siPDja9FXxFLiA.jpeg</url>
            <title>Stories by Gergő Mészáros on Medium</title>
            <link>https://medium.com/@gergmszros?source=rss-934df357ec29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:17:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gergmszros/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[How to use apollo as a state container]]></title>
            <link>https://medium.com/swlh/how-to-use-apollo-as-a-state-container-2d517ac410ee?source=rss-934df357ec29------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d517ac410ee</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo]]></category>
            <dc:creator><![CDATA[Gergő Mészáros]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 12:29:25 GMT</pubDate>
            <atom:updated>2022-04-28T12:51:33.304Z</atom:updated>
            <content:encoded><![CDATA[<p>I started using apollo as part of a legacy project that used both graphql and redux. Since apollo has a very good caching system you don’t really want to store the data you get from the backend in a redux store, but we had to store some data — like selected item’s ids — that only existed on the client side. Because of that for me it felt like using two different state container in the same project, and just like you don’t want to use redux and mobx in the same application, it just felt wrong to use redux and apollo, so I started to look for a different way to achieve my goals.</p><p>One obvious choice would be react context, but it is not so good if you want to avoid unnecessary re-renders. Still if you only want to store some really simple value that doesn’t change that often, I think react context is a good way to store your data.</p><p>But in my case I was working on a complex application that had a lot of data to store, like selected values or filters etc., so I kept looking and found that apollo has this so called local-only fields and it is exactly what I needed, so I decided to use it for local state management. Let’s take a look how someone can use it.</p><p>Our example project consists of a table with a list of planets which comes from a dummy API and users can select these planets and we’re going to store the selected ids in apollo.</p><p>I will start with a typescript react app:</p><pre>npx create-react-app apollo-state-container --template typescript</pre><p>Then add a few libs that we going to need, I suggest to use yarn, npm can cause dependency issues with graphql.</p><pre>yarn install <a href="http://twitter.com/apollo/client">@apollo/client</a> graphql  <a href="http://twitter.com/mui/material">@mui/material</a> <a href="http://twitter.com/emotion/react">@emotion/react</a> <a href="http://twitter.com/emotion/styled">@emotion/styled</a> apollo immer</pre><p>With the following script we will download the graphql schema from the dummy API, we will need that to generate our types later.</p><pre>yarn apollo service:download --endpoint=https://swapi-graphql.netlify.app/.netlify/functions/index graphql-schema.json</pre><p>Next step is to display the data we get from the API (link to github is at the end of the article):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*day8MLpud7KHTJY7rjf03w.png" /></figure><p>Now the tricky part: we need to store the selected planets, and every time a user makes any change we need to display the updated list at the top. With redux you would implement a store for this, with apollo we need to do something similar but we’re going to extend the schema we downloaded earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*dyQZEy2cpM9B6K0LwUQCww.png" /></figure><p>We extend the Root with a new query, since this query only exists on the frontend we also need to tell apollo how that query looks like. Our selected planets query will contain a key called planets, which is an array of “Planet”s. “Planet” is something that already exists in the original schema we just reuse it here, no need the implement that type.</p><p>Let’s try to write a query that uses our newly implemented type, the important thing here is the “@client” part, rest is just like any other query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DOFwsZurxaeDnIUg-ndcGA.png" /></figure><p>Since our selected planets are using the Planet type, we can request any prop of the Planet here. Now that the query is out there we can just run the code that will generate typescript file for us:</p><pre>yarn apollo client:codegen ./src/types.ts --target=typescript --outputFlat --no-addTypename --localSchemaFile=graphql-schema.json,graphql-local.graphql</pre><p>One more step to finish, let’s display the selected items:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*1ZtPtjtrnvZu9aMWrFgXdg.png" /></figure><p>You can check out the github repo <a href="https://github.com/mgergo90/apollo-state-container">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d517ac410ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-use-apollo-as-a-state-container-2d517ac410ee">How to use apollo as a state container</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marble testing in React]]></title>
            <link>https://medium.com/swlh/marble-testing-in-react-ba0639441afa?source=rss-934df357ec29------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0639441afa</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gergő Mészáros]]></dc:creator>
            <pubDate>Thu, 14 May 2020 10:17:08 GMT</pubDate>
            <atom:updated>2020-05-14T19:17:36.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmGTWBiTnmjk0FHAwgxUJQ.png" /></figure><p>A few years ago I started to use rxjs for managing asynchronous processes (such as API calls) in my React applications. When it comes to react you need to write epics to connect these async functions to your redux store.</p><blockquote>It [epic] is a function which takes a stream of actions and returns a stream of actions. <strong>Actions in, actions out.</strong></blockquote><p>In this article I would like to make a brief introduction about writing tests for epics. If you are not familiar with marble diagrams and marble testing you can find more info <a href="https://rxjs-dev.firebaseapp.com/guide/testing/internal-marble-tests">here</a>.</p><p>Let’s start with a simple example where you need to call an API endpoint and dispatch the response you get.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb99bc2bce1258b777dfdccd332c6a0/href">https://medium.com/media/5eb99bc2bce1258b777dfdccd332c6a0/href</a></iframe><p>Ideally in a live code you need to move actions to a separate file, but for the sake of simplicity I will leave them in one place. Now we have an epic which every time “GET_REPOS_ACTION” action is dispatched will attempt to call the url and dispatch an another action based on the result. This is what actions in, actions out means.</p><p>Time to write some tests! First we need to import TestScheduler which will virtualize time, since you might want to use delay, debounceTime etc. you need to virtualize time instead of waiting for those events to happen which would make your test slow. So here our TestScheduler implementation:</p><pre>import { TestScheduler } from &#39;rxjs/testing&#39;;</pre><pre><em>const</em> testScheduler = new TestScheduler((<em>actual</em>, <em>expected</em>) <em>=&gt;</em> {<br>  expect(<em>actual</em>).toEqual(<em>expected</em>);<br>});</pre><p>TestScheduler needs a function as parameter, it will be used to compare the expected and actual values. Now that we have everything, it is time to decide what we actually should test. Our getRepos epic does not do much, but we can check if we get the right actions once the API call finished. Since making an actual request is not a good idea here, first let’s avoid that by mocking the getJSON function:</p><pre>jest.mock(&#39;rxjs/ajax&#39;);</pre><p>Since getJSON would return with an observable, we can simulate a successful / failed answer with a mocked observable that gives dummy data:</p><pre>const testUser = { id: 1, name: &#39;testUser&#39;};</pre><pre>jest.spyOn(RxjsAjax.ajax, &#39;getJSON&#39;).mockReturnValueOnce(<br>  cold(&#39;a-#|&#39;, {<br>    a: [testUser],<br>  }),<br>);</pre><p>Our mocked API call will do the followings: gives back a value { data: ‘TestData’} then waits one time unit, then throws an error and exits, this way we can test both expected behavior, it should look like this:</p><pre>expectObservable(output$).toBe(`a-b`, {<br>  a: getUsersSuccessAction([testUser]),<br>  b: getUsersErrorAction(&quot;error&quot;),<br>});</pre><p>If you compare the mock values and the expected values, you can clearly see the connection between them. First value will be a “success answer from the server” which should dispatch a success action, then wait one time unit and get an “error response” which should dispatch an error action.</p><pre>on the input we have: &quot;a-#&quot;<br>on the output we have &quot;a-b&quot;</pre><p>If you look at the getRepos epic you can see that we return an action in case of an error (catchError) that is why we have that action on the output when an error occur. Let’s put all those code parts together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18dbf24a18c510ea48e1eb6628e30a50/href">https://medium.com/media/18dbf24a18c510ea48e1eb6628e30a50/href</a></iframe><p>I hope this short introduction gives you an idea how to write your own test, once you understand the basic concept of it, it should come easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0639441afa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/marble-testing-in-react-ba0639441afa">Marble testing in React</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT HttpOnly authorization with Laravel and React]]></title>
            <link>https://medium.com/@gergmszros/jwt-httponly-authorization-with-laravel-and-react-1f2ffdc007d5?source=rss-934df357ec29------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2ffdc007d5</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gergő Mészáros]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 06:11:06 GMT</pubDate>
            <atom:updated>2019-09-23T06:12:03.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*qF01rfBZnlSkE39hkAIW-A.png" /></figure><h4>Vulnerabilities</h4><p>Most of the time I use the library called <a href="https://github.com/tymondesigns/jwt-auth">Jwt Auth</a> for authenticating in Laravel projects. The process is quite simple: send the login credentials to the API, it gives back a token which gets stored - most of the time in local storage -, then place that token into the header of each API call. There is one major issue with that solution: if you have a compromised script served from a CDN or if there is malicious code in one of your JavaScript libraries, they can steal the token out of local storage. So storing the token in a place where JavaScript can access it is a bad practice. HttpOnly cookie is a more secure place to put the token since no js code can access it. Fortunately, Laravel JW Auth library let you do that out of the box. It has multiple ways to authenticate logged-in users, looking for a token in cookies is one of them. On the other hand, cookie-based authentication has a low point too, it makes CSRF attacks possible. In order to overcome that vulnerability, we need to send unique tokens in the request header. Let’s see how it works with an example.</p><h4>Implementation</h4><p>Let’s start with an empty Laravel (I used v5.8.35 in this tutorial). You also need two php libraries:<a href="https://github.com/tymondesigns/jwt-auth"> jwt-auth</a> and <a href="https://github.com/barryvdh/laravel-cors">laravel-cors</a>. On their websites you will find info on how to install them.</p><p>First, a route must be implemented for login endpoint:</p><pre>&lt;?php<br><br>use Illuminate\Http\Request;<br><br>Route::middleware([&#39;api&#39;])-&gt;group(function () {<br>    Route::namespace(&#39;Auth&#39;)<br>        -&gt;prefix(&#39;auth&#39;)<br>        -&gt;name(&#39;auth.&#39;)<br>        -&gt;group(function () {<br>            Route::post(<br>                &#39;login&#39;, <br>                &#39;AuthController@login&#39;<br>            )-&gt;name(&#39;login&#39;);<br>    });<br>});</pre><p>Then we need a controller for that route:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Auth;<br><br>use App\Http\Controllers\Controller;<br>use App\Http\Requests\Auth\LoginRequest;<br>use App\Http\Resources\AuthResource;<br>use Illuminate\Http\JsonResponse;<br><br>class AuthController extends Controller<br>{<br>    /**<br>     * Return authenticated user.<br>     *<br>     * @param LoginRequest $request<br>     * @return JsonResponse<br>     */<br>    public function login(LoginRequest $request): JsonResponse<br>    {<br>        return (new AuthResource(auth()-&gt;user()))<br>            -&gt;response()<br>            -&gt;withCookie(<br>                &#39;token&#39;, <br>                auth()-&gt;getToken()-&gt;get(), <br>                config(&#39;jwt.ttl&#39;), <br>                &#39;/&#39;<br>            );<br>    }<br><br>}</pre><p>There are two classes that are not part of the Laravel library, one of them is LoginRequest which is responsible to authenticate the user by the given credentials and assign a csrf token for the user.</p><pre>&lt;?php<br><br>namespace App\Http\Requests\Auth;<br><br>use Illuminate\Foundation\Http\FormRequest;<br><br>class LoginRequest extends FormRequest<br>{<br>    /**<br>     * Determine if the user is authorized to make this request.<br>     *<br>     * @return bool<br>     */<br>    public function authorize(): bool<br>    {<br>        $credentials = $this-&gt;only(<br>            &#39;data.email&#39;, <br>            &#39;data.password&#39;<br>        )[&#39;data&#39;];<br>        return auth()<br>            -&gt;claims([&#39;csrf-token&#39; =&gt; str_random(32)])<br>            -&gt;attempt($credentials);<br>    }<br><br>    /**<br>     * Define validation rules.<br>     *<br>     * @return array<br>     */<br>    public function rules(): array<br>    {<br>        return [];<br>    }<br>}</pre><p>The other one is AuthResource and it generates a json response for this endpoint, you can read more about Laravel’s API resources <a href="https://laravel.com/docs/5.8/eloquent-resources">here</a>.</p><pre>&lt;?php<br><br>namespace App\Http\Resources;<br><br>use Illuminate\Http\Resources\Json\JsonResource;<br><br>class AuthResource extends JsonResource<br>{<br>    /**<br>     * Transform the resource into an array.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @return array<br>     */<br>    public function toArray($request)<br>    {<br>        return [<br>            &#39;id&#39; =&gt; $this-&gt;id,<br>            &#39;name&#39; =&gt; $this-&gt;name,<br>            &#39;email&#39; =&gt; $this-&gt;email,<br>            &#39;csrf_token&#39; =&gt; auth()-&gt;payload()-&gt;get(&#39;csrf-token&#39;),<br>        ];<br>    }<br>}</pre><p>At this point you should be able to execute a login request successfully and get back a cookie with jwt token and a csrf token in the json response, we’re going to need both of them. We have no issue with jwt token other than tell the ajax call to send cookies automatically (e.g. you have to set withCredentials property for axios). The request header must include the csrf token, if you use axios you need something like this:</p><pre>axios.defaults.headers.common[&#39;CSRF-Token&#39;] = &#39;My CSRF token&#39;;</pre><p>The jwt token will be validated automatically by the library but we need to take care of CSRF token validation.</p><pre>&lt;?php<br><br>namespace App\Http\Middleware;<br><br>use Illuminate\Auth\Access\AuthorizationException;<br>use Closure;<br><br>class CsrfMiddleware<br>{<br>    /**<br>     * Handle an incoming request.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @param  \Closure  $next<br>     * @return mixed<br>     */<br>    public function handle($request, Closure $next)<br>    {<br>        if (<br>          $request-&gt;header(&#39;csrf-token&#39;) !==<br>          auth()-&gt;payload()-&gt;get(&#39;csrf-token&#39;)<br>        ) {<br>            throw new AuthorizationException;<br>        }<br>        return $next($request);<br>    }<br>}</pre><p>Also, CsrfMiddleware needs to be added to the application’s route middleware list (app/Http/Kernel.php):</p><pre>protected $routeMiddleware = [<br>    ...</pre><pre>    &#39;csrf&#39; =&gt; \App\Http\Middleware\<em>CsrfMiddleware</em>::class,<br>    ...<br>];</pre><p>Now every route you protect with ‘auth’ and ‘csrf’ middleware must receive these tokens.</p><p>One important note: the front- and back-end must be on the same domain to make this work (they can have different subdomain thought).</p><p>I hope this short tutorial will help you build an HttpOnly cookie based authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2ffdc007d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>