<?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 Irene Oppo on Medium]]></title>
        <description><![CDATA[Stories by Irene Oppo on Medium]]></description>
        <link>https://medium.com/@souljuse?source=rss-9b5b007e572d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iUFC0uRpJbZRClZg.jpg</url>
            <title>Stories by Irene Oppo on Medium</title>
            <link>https://medium.com/@souljuse?source=rss-9b5b007e572d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:51:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@souljuse/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[Create a static website with authentication tutorial with React and Netlify Identity]]></title>
            <link>https://medium.com/leanpanda/create-a-static-website-with-authentication-tutorial-with-react-and-netlify-identity-3713be0908a0?source=rss-9b5b007e572d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3713be0908a0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[static-site]]></category>
            <dc:creator><![CDATA[Irene Oppo]]></dc:creator>
            <pubDate>Fri, 04 Jan 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-01-09T17:05:47.747Z</atom:updated>
            <content:encoded><![CDATA[<p>As an agency we frequently use <strong>Middleman</strong> in combination with <strong>DatoCMS</strong> for our projects because it is still one of the <strong>simplest and quick-to-develop solution</strong> to build a static website. Everything runs smoothly with Middleman until one has to deal with processes that require more complex dynamic interaction, the most demanded one being definitely<strong> authentication</strong>.</p><p>Since it is a widely spread problem we wanted to share this <strong>neat and easy to setup</strong> <strong>integration to our usual stack</strong>, that adds the possibility to manage <strong>authentication to any project</strong> without getting tangled in complicated Ajax and JQuery logic or having to switch to a Javascript based generator like Gatsby. <strong>React</strong> is in fact a much simpler tool to deal with dynamic interaction, it is quite simple to install and can be re-used multiple times for different projects. Moreover since we use <strong>Netlify </strong>to host our static websites we wanted to give a try to <strong>its Identity feature</strong> to manage users and authentication.</p><p>The experiment was a success and now we use this solution widely in our agency projects.</p><p>To sum it up here is the complete <strong>stack we chose for this tutorial:</strong></p><ul><li><strong>Middleman </strong>static website generator, but you can choose your favourite ;)</li><li><strong>React </strong>to create a user interface for the authentication part.</li><li><strong>Netlify</strong> to host our website and Netlify Identity to manage our signed users.</li><li><strong>DatoCMS </strong>to provide content.</li></ul><h4>The goal</h4><p>To make it easier for everybody to notice the “before and after” effect, we cloned a “The Office” fan site made with Middleman and DatoCMS that you can find among the DatoCMS examples sites. Download the original project <a href="https://github.com/datocms/middleman-example">here</a>.</p><p>The goal is to make the seasons page accessible only to those who have an account, like it was premium content. For the purpose of this tutorial we will just show/hide the link, but the next step would be to implement a <strong>better discrimination using a lambda function</strong> that renders the content via React only to the signed in user.</p><p>This post does not want to go into some of the deeper technicalities but aims at showing the logic behind our decision to use this stack and to share a little bit of knowledge with a working example :)</p><p>The final result will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*N7jShY0Jw8T6PbBWJHp8eg.gif" /></figure><p>You can visit the complete site <a href="https://static-authentication-example.netlify.com/">here</a>, and download the full project <a href="https://gitlab.com/cantierecreativo/static-authentication-example">here</a>.</p><h3>Please identify yourself</h3><p>Netlify offers two options to manage the Identity feature, a <a href="https://github.com/netlify/netlify-identity-widget"><strong>widget</strong></a> that provides a quick solution, and an open source <a href="https://github.com/netlify/gotrue-js"><strong>GoTrue JS library</strong></a>, that basically exposes the methods used by the widget. The big perk of the library, in opposition to the ready-made Netlify Identity widget, is that it allows you to design your own interface and to keep in line with your brand identity and enable continuity in the overall user experience without significantly adding to your page weight.</p><h4>Netlify super quick setup</h4><p>We chose to be faithful to our web-designer and added Netlify Identity Javascript client library.</p><pre>yarn add gotrue-js</pre><p>To allow Netlify to manage the identities on your website you will have to activate “identity” from your Netlify account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*68OzDaPfxAn9N3HfXzA9MA.gif" /><figcaption>Enable Netlify Identity</figcaption></figure><p>For the purpose of this tutorial we enabled the <strong>signup without email confirmation</strong> option and we will only use the signup/signin methods, but you can experiment with all <a href="https://github.com/netlify/gotrue-js">GoTrueJS </a>options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNF3iUpVbmw_mwDTQ2VUIw.png" /></figure><h3>React to the rescue</h3><p>Independently from what you chose as static site generator we will let React discriminate who can see some premium content. So basically we want React to take care of:</p><ul><li>Rendering a signin/signout button.</li><li>Displaying a signin/signup form that allows a user to authenticate.</li><li>Hiding/showing some content that is accessible only if the user is logged in.</li></ul><p>In the javascripts create a folder named “auth” to separate your React files from other scripts. Then an index.js file that “attaches” React to static html.</p><pre>import ReactDOM from &quot;react-dom&quot;;<br>import React from &quot;react&quot;;<br>import App from &quot;./App&quot;;</pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;react-root&quot;));</pre><p>Your tree should look like this</p><pre>|- source <br>  ...<br>  |- javascripts <br>    |- auth<br>      |- App.js<br>      |- AuthBar.js<br>      |- AuthForm.js<br>      |- index.js</pre><p>You will need to setup Webpack and Babel, <a href="https://www.robinwieruch.de/minimal-react-webpack-babel-setup/">here</a> is a tutorial for the minimal setup.</p><h4>Routing</h4><p>Our <strong>App.js </strong>file will serve as the router of our React app and will render the proper component following the authentication logic. To do that we use React router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab9b07d65e0c05a0c4a508ea708429f/href">https://medium.com/media/aab9b07d65e0c05a0c4a508ea708429f/href</a></iframe><p><strong>AuthBar.js</strong> will provide the authentication menu and will be rendered as a part of the main navigation bar using <a href="https://reactjs.org/docs/portals.html">React portal</a>. So in our navbar.html we will have to add a div with an id (“#header-auth-navbar”) to “attach” the React component.</p><pre>header.main-navigation<br>  ...<br>  = link_to &quot;Homepage&quot;, &quot;/index.html&quot;<br>  #header-auth-navbar</pre><h4>Check if a user is logged in</h4><p>Before we create our authorization menu we need to implement a method that checks if the user is logged in, in order to display the right content (premium /regular, logout/ signin button).</p><p>To do that we create a <a href="https://reactjs.org/docs/higher-order-components.html">HOC component</a> that will listen if the current user has changed and updates the DOM accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href">https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href</a></iframe><h4>The authentication menu</h4><p>At the bare minimum an authentication navbar page should render a <strong>signin</strong> link if you are not logged in, or a <strong>logout </strong>link with a welcome message if you are. In addition to that we also want to show the “seasons” link only to a registered user. To do that we just check on the props.currentUser passed by our HOC component.</p><p>Signin link will point to the route we created in the router while logout will call the <strong>GoTrueJS method .logout()</strong> that deletes the current session and redirects to the home page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe91741793412ffc2528177c359cec96/href">https://medium.com/media/fe91741793412ffc2528177c359cec96/href</a></iframe><h4>The authentication form</h4><p>The logic of a signin and a signup form are similar though they make separate API calls. For the purpose of this tutorial we will tackle only the sign in component while in the <a href="https://gitlab.com/cantierecreativo/static-authentication-example">full example project</a> we switch between the signin/signup actions according to the route.</p><p>We will use <strong>Formik </strong>to build up the form, because it provides some useful methods to manage the component state. In Formik’s .onSubmit() function we will call the GoTrueJS library method .<strong>login()</strong> providing three arguments: email, password and a third argument that saves the current session (not documented on the Netlify docs). The query will check if an entry with that email exists in your Netlify project and then will save a session with an expiring date, otherwise will save the error message in the component’s state.</p><p>You can render the error by checking if this.state.error is not undefined.</p><pre>auth.login(values.email, values.password, true)<br>  .then(response =&gt; {<br>    actions.setSubmitting(false);<br>    Alert.success(&#39;You signed in successfully!&#39;);<br>    this.props.history.push(&quot;/&quot;);<br>  })<br>  .catch(error =&gt; {<br>    this.setState({error: error.json.error_description});<br>    actions.setSubmitting(false);<br>  });</pre><p>A SignIn Form should look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551e782c1dd8fd895f6531d9176801a5/href">https://medium.com/media/551e782c1dd8fd895f6531d9176801a5/href</a></iframe><p>Once you are logged in you should see the link to the premium content, a welcome message and the logout link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXV7d9rwVEocgn2P-Aln-A.png" /></figure><p>In conclusion we found out that adding such an authentication procedure has a lot of pros because it unlocks the possibility to create a complex website, with, for example, an admin area, premium users services etc. while keeping all the advantages of having a static website!</p><p><em>Originally published at </em><a href="https://www.leanpanda.com/blog/2019/01/04/create-a-static-website-with-authentication-tutorial-with-react-and-netlify-identity/"><em>www.leanpanda.com</em></a><em> on January 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3713be0908a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leanpanda/create-a-static-website-with-authentication-tutorial-with-react-and-netlify-identity-3713be0908a0">Create a static website with authentication tutorial with React and Netlify Identity</a> was originally published in <a href="https://medium.com/leanpanda">LeanPanda</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial per creare un sito statico con sistema di autenticazione con React e Netlify Identity]]></title>
            <link>https://medium.com/cantiere-creativo/ttutorial-per-creare-un-sito-statico-con-sistema-di-autenticazione-con-react-e-netlify-identity-d9facb07cf09?source=rss-9b5b007e572d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9facb07cf09</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[middleman]]></category>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[jamstack]]></category>
            <dc:creator><![CDATA[Irene Oppo]]></dc:creator>
            <pubDate>Fri, 04 Jan 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-01-09T20:49:55.814Z</atom:updated>
            <content:encoded><![CDATA[<p>Come agenzia utilizziamo di frequente <strong>Middleman in combinazione con DatoCMS</strong> per i nostri progetti, perché è sicuramente <strong>una delle soluzioni più semplici e veloci per costruire un sito web statico</strong>. Tutto funziona senza problemi con Middleman fino a non si ha a che fare con processi che richiedono una più complessa interazione dinamica, e il più richiesto è sicuramente la <strong>possibilità di autenticare degli utenti</strong>.</p><p>Poiché si tratta di un problema diffuso, abbiamo voluto condividere con il resto del mondo l’esperimento di integrazione al nostro solito stack di Netlify Identity, poiché si è rivelata una <strong>soluzione ordinata e di facile installazione</strong>. La comodità di usare React ha reso il tutto ancora più semplice eliminando il problema rimanere impigliati in Ajax e JQuery o di dover passare a generatori Javascript, come Gatsby. <strong>React</strong> è infatti uno strumento molto più semplice e duttile per gestire l’interazione dinamica, è abbastanza semplice da installare e può essere riutilizzato più volte per diversi progetti. Inoltre, dal momento che utilizziamo Netlify per hostare i nostri siti web statici abbiamo voluto dare una chance della sua feature <strong>Identity</strong> che permette la gestione di utenti e dell’ autenticazione.</p><p>L’esperimento è stato un successo e ora usiamo questa soluzione ampiamente a Cantiere Creativo.</p><p>Per riassumere, ecco il completo stack che abbiamo scelto per questo tutorial:</p><ul><li><strong>Middleman</strong> come generatore, ma puoi usare il tuo preferito ;)</li><li><strong>React</strong> per creare un’interfaccia utente per la parte di autenticazione.</li><li><a href="https://www.netlify.com/">Netlify</a> per hostare il nostro sito web e <a href="https://www.netlify.com/docs/identity/">Netlify Identity</a> tramite la libreria <strong>GoTrue JS</strong> per gestire i nostri utenti iscritti.</li><li><a href="https://www.datocms.com/">DatoCMS</a> per gestire i contenuti.</li><li><a href="https://github.com/netlify/gotrue">GoTrue API</a> servizio API open-source per gestire le autenticazioni.</li></ul><h4>L’obiettivo</h4><p>Per rendere più evidente l’effetto “prima e dopo”, abbiamo clonato un fan site di “The Office” fatto con Middleman e DatoCMS che potete trovare tra gli esempi di siti di DatoCMS. Scarica il progetto originale <a href="https://github.com/datocms/middleman-example">qui</a>. L’obiettivo è quello di rendere pagina “Seasons” accessibile solo a coloro che dispongono di un account, come se fosse una pagina di contenuti premium.</p><p>Ai fini del tutorial dimostreremo solo come mostrare/nascondere il link alla pagina in questione, ma il passo successivo sarebbe quello di rendere la <strong>discriminazione più efficiente tramite una funzione lambda</strong> che restituisce il contenuto via React solo per l’ utente autenticato. Questo post non vuole andare in profondità con i tecnicismi, ma mira a condividere la logica dietro la nostra decisione di utilizzare questo stack e a condividere un po ‘ di conoscenza con un esempio funzionante :)</p><p>Il risultato finale sarà più o meno così</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*YjznVVo9QnsZuSpe.gif" /></figure><p>Puoi vedere il progetto completo deployato <a href="https://static-authentication-example.netlify.com/">qui</a>, e scaricare la repo <a href="https://gitlab.com/cantierecreativo/static-authentication-example">qui</a>.</p><h3>Prego, fornisca i suoi dati</h3><p>Netlify offre due opzioni per gestire Identity, un <a href="https://github.com/netlify/netlify-identity-widget"><strong>widget</strong></a> per una soluzione rapida, e una libreria open source <a href="https://github.com/netlify/gotrue-js"><strong>GoTrue JS</strong></a>, che, fondamentalmente, espone i metodi utilizzati dal widget. Il grande vantaggio della libreria, in opposizione al widget,è che permette di disegnare la propria interfaccia, restando in linea con l’ identità di brand e garantendo la continuità nell’esperienza complessiva dell’utente senza aggiungere peso alla pagina.</p><h4>Netlify e il suo setup super veloce</h4><p>Abbiamo preferito essere fedeli al nostro web-designer e abbiamo scelto il client di Netlify Identity.</p><p>Per consentire a Netlify di gestire gli utenti del tuo sito devi attivare “Identity” dal tuo account Netlify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*2tmR8a9On7s1y6_f.gif" /></figure><p>Ai fini del tutorial abbiamo attivato l’opzione che permette l’iscrizione senza email di conferma e dimostreremo solo i metodi di signup/signin, ma invitiamo a sperimentare con tutte le possibilità che offre GoTrue JS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rTJs9l05FiWq-Hmg.png" /></figure><h3>React all’assalto</h3><p>Indipendentemente da quale generatore abbiate scelto lasceremo che sia React a realizzare l’interfaccia discriminando chi può visualizzare i nostri contenuti premium.</p><p>Quindi fondamentalmente affidiamo a React i seguenti compiti:</p><ul><li>Il Rendering di un bottone signin/logout.</li><li>Mostrare un modulo di iscrizione/registrazione che consenta all’utente di autenticarsi.</li><li>Nascondere/mostrare il contenuto premium all’utente.</li></ul><p>In javascript creare una cartella denominata “auth” per separare i file React dagli altri script. Poi un index.js file che permetta a React di “agganciarsi” al nostro html statico.</p><pre>import ReactDOM from &quot;react-dom&quot;; import React from &quot;react&quot;; <br>import App from &quot;./App&quot;; </pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;react-root&quot;));</pre><p>Il tree dovrebbe avere una struttura simile</p><pre>|- source <br>  ... <br>  |- javascripts <br>  |- auth <br>    |- App.js <br>    |- AuthBar.js <br>    |- AuthForm.js <br>   |- index.js</pre><p>Prima di attivare React dovreste configurare Webpack e Babel<a href="https://www.robinwieruch.de/minimal-react-webpack-babel-setup/">, qui</a> trovate un tutorial per un setup minimale.</p><h4>Routing</h4><p>Il file <strong>App.js</strong> servirà come router della nostra React app e per restituire il componente appropriato seguendo la logica di autenticazione. Per farlo utilizziamo React Router.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c355f5d516f1d7d7003b39e3949d38a4/href">https://medium.com/media/c355f5d516f1d7d7003b39e3949d38a4/href</a></iframe><p><strong>AuthBar.js</strong> si occuperà di mostrare il menu di autenticazione come parte della barra di navigazione principale, tramite <a href="https://reactjs.org/docs/portals.html">React portal</a>. Quindi, nel nostro navbar.html dovremo aggiungere un div con un id (“#header-auth-navbar”) per “agganciare” il componente React.</p><pre>header.main-navigation ... = link_to &quot;Homepage&quot;, &quot;/index.html&quot; #header-auth-navbar</pre><pre>header.main-navigation<br>  ...<br>  = link_to &quot;Homepage&quot;, &quot;/index.html&quot;<br>  #header-auth-navbar</pre><h4>Controllare se un utente è loggato</h4><p>Per prima cosa abbiamo bisogno di implementare un metodo che verifichi se l’utente è loggato, in modo da poter discriminare il contenuto mostrato.<br>Per farlo creiamo un componente <a href="https://reactjs.org/docs/higher-order-components.html">HOC</a> che stia in ascolto sull’utente corrente aggiorni il DOM di conseguenza.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href">https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href</a></iframe><h4>Il menu di autenticazione</h4><p>In aggiunta abbiamo bisogno di mostrare il link alla pagina “Seasons” solo agli utenti autenticati. Per farlo ci basta controllare la props.currentUser passati dal nostro componente HOC.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href">https://medium.com/media/ff5b2fa8449151847e2ca7844e6d580d/href</a></iframe><p>Il link di sign in punterà alla rotta che abbiamo creato nel router, mentre il logout chiamerà il metodo GoTrueJS .logout() che elimina la sessione corrente e dovrà reindirizzare alla pagina iniziale.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe91741793412ffc2528177c359cec96/href">https://medium.com/media/fe91741793412ffc2528177c359cec96/href</a></iframe><h4>Il form di autenticazione</h4><p>La logica di un form di registrazione o autenticazione è simile anche se hanno bisotno di chiamate API differenti, quindi per ora tratteremo solo l’azione di sign in, mentre nel progetto di esempio divideremo le due azioni di signin/signup in base all’url. <br>Useremo Formik per costruire il form, perché fornisce alcuni metodi utili per gestire lo stato del componente. Usando la funzione .onSubmit() di Formik, al momento dell’invio del form chiameremo il metodo .login() di GoTrueJS passandogli tre argomenti: e-mail, password e un terzo argomento che salva la sessione corrente (non documentato su Netlify docs). La query controllerà se esiste una utente con quella mail nel progetto Netlify e quindi si salverà una sessione con una data di scadenza, o, in caso contrario, salverà il messaggio di errore dello stato del componente. <br>A quel punto è possibile printare l’errore verificando se esiste this.state.error.</p><pre>auth.login(values.email, values.password, true)<br>  .then(response =&gt; {<br>    actions.setSubmitting(false);<br>    Alert.success(&#39;You signed in successfully!&#39;);<br>    this.props.history.push(&quot;/&quot;);<br>  })<br>  .catch(error =&gt; {<br>    this.setState({error: error.json.error_description});<br>    actions.setSubmitting(false);<br>  });</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551e782c1dd8fd895f6531d9176801a5/href">https://medium.com/media/551e782c1dd8fd895f6531d9176801a5/href</a></iframe><p>Come risultato una volta loggato l’utente dovrebbe vedere il link per il contenuto premium, un messaggio di benvenuto e il collegamento al logout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXV7d9rwVEocgn2P-Aln-A.png" /></figure><p>In conclusione le potenzialità di introdurre un sistema di autenticazione in un sito statico sono molte. Tramite l’aggiunta di questa semplice logica si può cominciare a costruire un sito web complesso, partendo anche da questo esempio, con, per esempio, un’area admin, utenti premium, servizi etc. mantenendo tutti vantaggi di avere un sito web statico!</p><p><em>Originally published at </em><a href="https://www.cantierecreativo.net/blog/2019/01/04/tutorial-per-creare-un-sito-statico-con-sistema-di-autenticazione-con-react-e-netlify-identity/"><em>www.cantierecreativo.net</em></a><em> on January 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9facb07cf09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cantiere-creativo/ttutorial-per-creare-un-sito-statico-con-sistema-di-autenticazione-con-react-e-netlify-identity-d9facb07cf09">Tutorial per creare un sito statico con sistema di autenticazione con React e Netlify Identity</a> was originally published in <a href="https://medium.com/cantiere-creativo">Cantiere Creativo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create an inverse relationships plugin on DatoCMS]]></title>
            <link>https://medium.com/datocms/how-to-create-an-inverse-relationships-plugin-on-datocms-253e7370aedc?source=rss-9b5b007e572d------2</link>
            <guid isPermaLink="false">https://medium.com/p/253e7370aedc</guid>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[building]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Irene Oppo]]></dc:creator>
            <pubDate>Thu, 22 Nov 2018 17:01:02 GMT</pubDate>
            <atom:updated>2018-11-22T17:01:02.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*L6yOwnLz3ny50bylkMFe_Q.png" /></figure><p>Just a couple of weeks ago we released the <a href="https://www.datocms.com/blog/build-the-perfect-cms-introducing-plugins/">Plugins SDK</a>, that enable the developers community to fully customize every project’s administrative area.</p><p>Let’s say we have a project that has, for example, an Author model and a Post model and each post is linked to an author by a single link field. In DatoCMS we can see which author created the post by navigating into the single post… but it is not possible to see which posts each author has written!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtwMDJjhyGsQfyThJN8fxw.png" /></figure><p>Being able to see inverse relationships it’s a <a href="https://github.com/datocms/feature-requests/issues/92">pretty common need</a>: thankfully we can build a plugin for that, let’s see how!</p><h3>Run the project generator</h3><p>To start straight away with the development and avoid writing boilerplate code, we’ve prepared a super-handy <a href="https://github.com/datocms/generator-datocms-plugin">Yeoman generator</a>.</p><p>Let’s create the folder that will contain the skeleton of our plugin and, once inside the folder, let’s run the generator:</p><pre>mkdir inverse-relationships<br>cd inverse-relationships<br>npx -p yo -p generator-datocms-plugin -c ‘yo datocms-plugin’</pre><p>Here’s a quick video of the tool in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F301886498%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F301886498&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F740536685_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/090402dbf4a3233df5579f747614d224/href">https://medium.com/media/090402dbf4a3233df5579f747614d224/href</a></iframe><p>As you can see, a number of questions will be prompted. Some of them are quite obvious (ie. the plugin name), others require a little more understanding of what’s going on, so let’s see them in detail.</p><h3>Plugin type</h3><p>DatoCMS supports <a href="https://www.datocms.com/docs/plugins/introduction/#types-of-plugins">three types of plugin</a>: <em>field editors</em>, <em>field-addons</em> and <em>sidebar widgets</em>.</p><p>While the first two types of plugin operate on top of a particular field replacing/enhancing the default editor that DatoCMS provides, sidebar widget are rendered.. <em>duh</em>, on the sidebar of the record editor.</p><p>Since this plugin applies to an entire record instead of a single field, we’ll pick the <em>Sidebar widget</em> option.</p><h3>Field types the plugin is compatible with</h3><p>DatoCMS plugins need to be <a href="https://www.datocms.com/docs/plugins/install/#assigning-a-plugin-to-a-field">assigned to a field in one of your models</a> to come alive, so while creating new plugins you need to declare which kind of fields your plugin supports.</p><p>While it’s quite obvious that you need to assign <em>field editors</em> plugins and <em>field-addons</em> plugins to a field, it might be less clear why this also applies to <em>sidebar widgets</em>, right? Well, the reason is that the sidebar widget might want to use the field’s value to store some data (and yes, in case you’re wondering, the underlying field won’t be shown on the interface).</p><p>In any case, our sidebar widget plugin won’t read/store any data, so we can just choose any field type (ie. JSON) and move on to the next question.</p><h3>Configuration parameters</h3><p>Parameters allow the final user to customize the plugin, and you as the developer are in charge of deciding to which degree you want your plugin to be customizable.</p><p>Global parameters are set just once for the whole project. In this case we need to ask the final user the API token to use to query the DatoCMS API and get the actual inverse relationships.</p><p>Instance variables, on the other hand, allow the final user to insert different settings every time the plugin gets applied on a field.</p><p>Our plugin requires two instance variables: the first one will store the name of the model you want to connect to (ie. post), the other will store the field that hosts the inverse relation between the two (ie. author).</p><p>Parameters need to be expressed in JSON. The format is pretty straight-forward, but feel free to <a href="https://www.datocms.com/docs/plugins/creating-a-new-plugin/#configuration-parameters">take a look at our documentation</a> for all the nitty gritty details:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f3a64475e016ca43197b782ae623738/href">https://medium.com/media/5f3a64475e016ca43197b782ae623738/href</a></iframe><h3>Alright, I’m done configuring stuff!</h3><p>If everything went right, you should see in your DatoCMS project an already configured plugin similar to this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMGDzsYa72LiVwX8j6GC2w.png" /></figure><p>As you can see, in this page you can already insert the only global configuration parameter we have, the DatoCMS API token. Let’s do so and hit the Save button.</p><h3>Assign the plugin to a JSON field</h3><p>Now that the plugin is installed in the project, you need to apply it to a JSON field to see it working.</p><p>Navigate to the Author model (Settings &gt; Models &gt; Author) and add the JSON field that will host the plugin. You will notice that in the presentation tab you can select our plugin as the <em>Field editor</em> option and fill-in the instance configuration parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*_xBO_3fusrVJFD0mkUz4cA.png" /></figure><h3>See the plugin working</h3><p>Technically speaking, plugins are small HTML5 applications that exist in a sandboxed &lt;iframe&gt; and interact with the main DatoCMS webapp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIWY61kjnGAPTkyXpzyLfQ.png" /></figure><p>As you can see, our generator already setup the <a href="https://www.datocms.com/docs/plugins/entry-point/">Entry point</a> of our plugin so that it points to a tunnel connected to our local project. That is, using the raw localhost URL would give us some <em>mixed content </em>errors due to the fact that the local development server runs in HTTP while the main DatoCMS webapp runs in HTTPS.</p><p>Anyway, just start your local webpack development server with:</p><pre>yarn start</pre><p>Once the server starts, go to one of your authors.. and voilà! You should see a glorious “Hello, world!” awaiting for you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk2n3SkWjn7t_Jsfzj8XRQ.png" /></figure><h3>Write some code</h3><p>Alright, the setup part is finished, it is time to get to the coding! Let’s take a look at src/index.js file:</p><pre>import ‘./style.sass’;</pre><pre>window.DatoCmsPlugin.init((plugin) =&gt; {<br> plugin.startAutoResizer();</pre><pre>const container = document.createElement(‘div’);<br> container.classList.add(‘container’);<br> container.textContent = ‘Hello, world!’;</pre><pre>document.body.appendChild(container);<br>});</pre><p>The project already includes our <a href="https://www.datocms.com/docs/plugins/sdk-reference/">Plugin SDK</a>, which exposes the DatoCmsPlugin.init() method. Its callback will be called when the cross-window communication between our plugin and the DatoCMS main webapp is in place, so all the code needs to be executed inside of it. The plugin.startAutoResizer call will make sure the iframe will automatically resize whenever the content of the page changes.</p><p>Alright, let’s start adding a title to the widget:</p><pre>const container = document.createElement(‘div’);<br>container.classList.add(‘container’);</pre><pre>const title = document.createElement(‘h4’);<br>title.textContent = ‘Linked content’;</pre><pre>document.body.appendChild(container);<br>container.appendChild(title);</pre><p>Great, now we can add to our project the datocms-client package, so that we’ll be able to query the DatoCMS API to get the inverse relationships:</p><pre>yarn add datocms-client</pre><p>Once installed, we can require the package and instanciate the DatoCMS SiteClient using the datoCmsApitToken global parameter we configured earlier:</p><pre>import { SiteClient } from ‘datocms-client;</pre><pre>window.DatoCmsPlugin.init((plugin) =&gt; {<br> plugin.startAutoResizer();<br> <br> // …<br> <br> const client = new SiteClient(plugin.parameters.global.datoCmsApiToken);<br>});</pre><h4>Building up the query</h4><p>The next thing to do is building the right query to get what you need, in this case all the Post records that are linked to a specific author.</p><p>The plugin object holds a couple of properties that are essential here. The first one is plugin.itemTypes that returns all the project’s models. We can use it to get our Post model:</p><pre>const postItemType = Object.values(plugin.itemTypes).find(<br> itemType =&gt; itemType.attributes.api_key === plugin.parameters.instance.itemTypeApiKey<br>);</pre><p>The second is plugin.itemId , which is the ID of the current author record we’re seeing. Looks we’ve got everything to build the query now!</p><pre>const linkFieldApiKey = plugin.parameters.instance.fieldApiKey;</pre><pre>const query = {<br> ‘filter[type]’: postItemType.id,<br> [`filter[fields][${linkFieldApiKey}][is][]`]: plugin.itemId,<br> ‘page[limit]’: 10,<br> version: ‘current’,<br>};</pre><pre>client.items.all(query)</pre><p>This returns all the blog posts that have the current record as its author. For each one of them we can create a link element and then append it to the iframe:</p><pre>dato.items.all(query).then((items) =&gt; {<br> items.forEach((item) =&gt; {<br> const link = document.createElement(‘a’);<br> link.textContent = “title placeholder”;<br> const url = `#`;<br> link.href = url;<br> link.target = ‘_top’;<br> link.classList.add(‘link’);<br> container.appendChild(link);<br> });<br>})<br>.catch((error) =&gt; {<br> console.log(error);<br>});</pre><p>We now need to find out which is the title field for the Post model:</p><pre>const titleFieldId = postItemType.relationships.title_field.data.id;<br>const titleField = plugin.fields[titleFieldId];</pre><p>Now we can build the url and show the appropriate title. Of course our item could be localized, so in this case we should get the title in the main locale:</p><pre>if (titleField.attributes.localized) {<br> const mainLocale = plugin.site.attributes.locales[0];<br> link.textContent = item[titleField.attributes.api_key][mainLocale];<br>} else {<br> link.textContent = item[titleField.attributes.api_key];<br>}</pre><pre>const url = `/editor/item_types/${postItemType.id}/items/${item.id}/edit`;</pre><p>Finally you should be able to see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*6hXJE4NzW2vvylUXNWNAaQ.png" /><figcaption>Add your favourite CSS styling and there you have your first custom plugin!</figcaption></figure><h4>Share your plugin to the world</h4><p>It is now time to share your work with the community!</p><p>Open your package.json and README.md and make sure all the info is correct following <a href="https://www.datocms.com/docs/plugins/publishing/">our documentation</a>.</p><p>Consider adding a nice cover picture and a preview GIF image so that when the plugin will be displayed <a href="https://www.datocms.com/plugins/">our plugin catalog</a> it will be easier to decide that this is the plugin we want.</p><p>When everything is ready, run npm publish, and you’re good to go! The plugin will be added to the catalog in 10 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAyKnSoD8znQErfxdNKQmw.png" /></figure><p>You can install the final plugin <a href="https://www.datocms.com/plugins/i/datocms-plugin-inverse-relationships/">from our catalog</a> or take a look at the complete code in this <a href="https://github.com/datocms/plugins/tree/master/inverse-relationships">Github repo</a>.</p><p><em>Originally published at </em><a href="https://www.datocms.com/blog/how-to-create-an-inverse-relations-plugin/"><em>www.datocms.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253e7370aedc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datocms/how-to-create-an-inverse-relationships-plugin-on-datocms-253e7370aedc">How to create an inverse relationships plugin on DatoCMS</a> was originally published in <a href="https://medium.com/datocms">DatoCMS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>