<?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 Jeffrey Yan on Medium]]></title>
        <description><![CDATA[Stories by Jeffrey Yan on Medium]]></description>
        <link>https://medium.com/@j3y?source=rss-7404641a1056------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*giqyo4LUL_1sOx7N.jpg</url>
            <title>Stories by Jeffrey Yan on Medium</title>
            <link>https://medium.com/@j3y?source=rss-7404641a1056------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:43:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j3y/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[Beyond basic knex.js database migrations]]></title>
            <link>https://medium.com/@j3y/beyond-basic-knex-js-database-migrations-22263b0fcd7c?source=rss-7404641a1056------2</link>
            <guid isPermaLink="false">https://medium.com/p/22263b0fcd7c</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jeffrey Yan]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 18:07:52 GMT</pubDate>
            <atom:updated>2018-04-05T18:07:52.548Z</atom:updated>
            <content:encoded><![CDATA[<p>I thought I’d write a quick summary around using <a href="http://knexjs.org/">knex.js</a> for migrations beyond what introduction tutorials show. The official documentation details them pretty well, plus other <a href="https://alexzywiak.github.io/running-migrations-with-knex/index.html">guides</a> give a nice step-by-step overview on creating migrations from scratch.</p><p>One thing I’ve found is that for most guides, there’s not really any guidance on how to manage SQL migrations beyond what’s in the base tutorial. This includes:</p><ul><li>Creating tables</li><li>Adding columns</li><li>Setting null conditions and defaults</li><li>Adding foreign key constraints</li><li>Indexes</li></ul><p>Whenever anything custom is required, a trusty knex.raw() can be used with more complex SQL statements.</p><h3>Background</h3><p>The typical knex.js migrations folder structure looks something like:</p><pre>/db<br>  /migrations<br>    20180404114353_initial.js<br>    20180405123128_add_view.js</pre><p>The file 20180404114353_initial.js could look something like:</p><pre>module.exports.up = async function(knex) {<br>  await knex.schema.createTable(&#39;products&#39;, table =&gt; {<br>    table.increments(&#39;id&#39;).primary();<br>    table.text(&#39;name&#39;).notNullable();<br>    table.integer(&#39;price&#39;);<br>  });<br>};</pre><pre>module.exports.down = async function(knex) {<br>  await knex.schema.dropTableIfExists(&#39;products&#39;);<br>};</pre><p>The next migration 20180405123128_add_view adds a basic view:</p><pre>module.exports.up = async function(knex) {<br>  await knex.raw(`<br>    CREATE OR REPLACE VIEW &quot;products_grouped&quot; AS (<br>      SELECT<br>        &quot;products&quot;.*, <br>        &quot;price&quot; &gt; 100 AS &quot;requires_signoff&quot;<br>      FROM &quot;products&quot;<br>    );<br>  `);<br>};<br>module.exports.down = async function(knex) {<br>    await knex.raw(&#39;DROP VIEW &quot;products_grouped&quot;;&#39;);<br>};</pre><p>Postgresql will be the SQL dialect of choice for this review, but it should be similarly applicable to other dialects. Similarly this is a node.js framework, so node.js will be the platform used when any code is required.</p><h3>The problem</h3><p>Imagine that this view needs to be updated later on with another column. We end up adding a new migration and now looks like:</p><pre>/db<br>  /migrations<br>    20180404114353_initial.js<br>    20180405123128_add_view.js<br>    20180406132347_update_view.js</pre><p>The migration file 20180406132347_update_view.js looks like:</p><pre>module.exports.up = async function(knex) {<br>  await knex.raw(&#39;DROP VIEW &quot;products_grouped&quot;;&#39;);<br>  await knex.raw(`<br>    CREATE OR REPLACE VIEW &quot;products_grouped&quot; AS (<br>      SELECT<br>        &quot;products&quot;.*, <br>        &quot;price&quot; &gt; 100 AS &quot;requires_signoff&quot;,<br>        EXTRACT(YEAR FROM &quot;created_at&quot;)::TEXT AS &quot;year&quot;<br>      FROM &quot;products&quot;<br>    );<br>  `);<br>};<br>module.exports.down = async function(knex) {<br>  await knex.raw(&#39;DROP VIEW &quot;products_grouped&quot;;&#39;);<br>  await knex.raw(`<br>    CREATE OR REPLACE VIEW &quot;products_grouped&quot; AS (<br>      SELECT<br>        &quot;products&quot;.*, <br>        &quot;price&quot; &gt; 100 AS &quot;requires_signoff&quot;<br>      FROM &quot;products&quot;<br>    );<br>  `);<br>};</pre><p>The down() function of new migration has to restore what the view previously was, so we end up copying the same view creation statement into the rollback. When you’re adding functions, views, triggers and constraints this can quickly get out of hand.</p><h3>Proposal</h3><p>I’ve found that keeping some discrete definitions immutable works really well. Essentially this means creating <em>versions of each function or trigger </em>such as v1.js, v2.js and so on.</p><p>Looking back on the example above, a slightly more maintainable structure could look like:</p><pre>/db<br>  /migrations<br>    20180404114353_initial.js<br>    20180405123128_add_view.js<br>    20180406132347_update_view.js<br>  /queries<br>    /views<br>      /products_grouped<br>        v1.js<br>        v2.js</pre><p>As the products_grouped view is updated, a new file v1.js or v2.js is created and is never changed.</p><p><strong>v1.js</strong></p><pre>module.exports.up = `<br>DROP VIEW IF EXISTS &quot;products_grouped&quot;;<br>CREATE OR REPLACE VIEW &quot;products_grouped&quot; AS (<br>  SELECT<br>    &quot;products&quot;.*, <br>    &quot;price&quot; &gt; 100 AS &quot;requires_signoff&quot;<br>  FROM &quot;products&quot;<br>);<br>`;</pre><pre>module.exports.down = &#39;DROP VIEW &quot;products_grouped&quot;;&#39;;</pre><p><strong>v2.js</strong></p><pre>module.exports.up = `<br>  DROP VIEW IF EXISTS &quot;products_grouped&quot;;<br>  CREATE OR REPLACE VIEW &quot;products_grouped&quot; AS (<br>    SELECT<br>      &quot;products&quot;.*, <br>      &quot;price&quot; &gt; 100 AS &quot;requires_signoff&quot;,<br>      EXTRACT(YEAR FROM &quot;created_at&quot;)::TEXT AS &quot;year&quot;<br>    FROM &quot;products&quot;<br>  );<br>`;</pre><pre>module.exports.down = require(&#39;./v1&#39;).up;</pre><p>Note that v1.js has an up() function which can be immediately used as the down function in v2.js. This may not always be possible, but often the up() of the previous version can be used as the base query for rollbacks.</p><p>The first migration that creates the view (20180405123128_add_view) will instead then look like:</p><pre>const v1 = require(&#39;../queries/views/products_grouped/v1&#39;);</pre><pre>module.exports.up = async function(knex) {<br>  await knex.raw(v1.up);<br>};</pre><pre>module.exports.down = async function(knex) {<br>  await knex.raw(v1.down);<br>};</pre><p>The view update migration () can then be changed accordingly to:</p><pre>const v2 = require(&#39;../queries/views/products_grouped/v2&#39;);</pre><pre>module.exports.up = async function(knex) {<br>  await knex.raw(v2.up);<br>};</pre><pre>module.exports.down = async function(knex) {<br>  await knex.raw(v2.down);<br>};</pre><h3>Summary</h3><p>This method of versioning blocks of SQL queries works well for many use cases and aims to follow <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principles. Older versions of the function can be reviewed easily and the migration path to newer versions is obvious.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22263b0fcd7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing multi-tenant applications on Node.js and objection.js]]></title>
            <link>https://medium.com/@j3y/developing-multi-tenant-applications-on-node-js-and-objection-js-7b73396a0ad4?source=rss-7404641a1056------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b73396a0ad4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jeffrey Yan]]></dc:creator>
            <pubDate>Sat, 03 Mar 2018 19:43:09 GMT</pubDate>
            <atom:updated>2018-03-03T19:43:09.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Node.js API dev tutorials give an overview of REST API basics. While these are a great guide for scaffolding out your CRUD methods, I’ve found there aren’t many resources for more complex problems. One such problem that comes up in many applications is multi-tenancy. Multi-tenancy refers to a single application instance supporting multiple <em>tenants</em> — which includes most SaaS web applications.</p><p>In this discussion I’ll be focusing on the Node.js platform, as well as RDBMS (specifically Postgres) as the database technology. The usage of Postgres opens up an option to use the <em>schema</em> concept as a tenant separation mechanism, which is referred to (but not used) later.</p><h3>Patterns</h3><p>Multi-tenancy implementations aren’t a binary concept, but rather a continuum of solutions depending on requirements. The continuum looks something like:</p><ul><li>An application backend per-tenant (webserver, database)</li><li>A single webserver served by databases per-tenant</li><li>A single webserver with a single database, served by database specific separation mechanisms (e.g. Postgres schemas)</li><li>A single webserver with a single database, with tenant data separated into their own tables</li><li>A single webserver with a single database, with shared tables mixing all tenant data</li></ul><p>Each of these solutions has trade-offs in terms of:</p><ul><li>Data isolation and security</li><li>Infrastructure costs and scalability</li><li>Development complexity</li><li>Difficulty of onboarding new tenants</li><li>Difficulty of modifying data structures for existing tenants</li></ul><p>These trade-offs are referred to in this detailed <a href="https://stackoverflow.com/questions/2213006/how-to-create-a-multi-tenant-database-with-shared-table-structures">stackoverflow post</a>, which has some useful linked references.</p><h4>The single table design</h4><p>Unfortunately there isn’t time to delve into every single implementation in this article. I’ll be specifically referring to the shared-table multi-tenancy pattern, sometimes referred to as row-based multi-tenancy. This pattern is more ideal for situations where there are <strong>many tenants each with relatively small amounts of data</strong>. <a href="https://stackoverflow.com/questions/44524364/postgresqls-schemas-for-multi-tenant-applications">This post</a> summarizes some trade-offs well.</p><p>When using Postgres, the option of <strong>schemas </strong>and <strong>views </strong>opens up the possibility of a <a href="https://stackoverflow.com/a/44530588/3649053">hybrid design </a>— where a schema will exist per tenant, with views providing a slice of the tenant data accordingly. Postgres views are essentially treated as stored queries, since they don’t store any data. The concept is useful but it does add another layer of detail to maintain (the schemas). These <strong>view queries</strong> look something like:</p><pre>CREATE VIEW “customers_view_ABCD” AS (<br>  SELECT *<br>  FROM “customers”<br>  WHERE “tenantId” = ‘ABCD’<br>)</pre><p>This query is relatively trival to generate dynamically, so doesn’t seem worth the maintenance complexity.</p><h4>objection.js</h4><p>The reason that <a href="https://github.com/Vincit/objection.js">objection.js</a> was chosen as the ORM of choice was due to it also exposing the powerful <a href="http://knexjs.org/">knex.js</a> interface. The power of the ORM can be leveraged when doing CRUD style queries such as find or insert. Then the knex.js query builder can be used when more power is required.</p><p>The best part about objection.js though is that these 2 styles can be used simultaneously in the same query. This leads to some potentially powerful filtering mechanics which aren’t discussed here. I ended up creating a <a href="https://github.com/tandg-digital/objection-filter">filtering convenience package</a> to leverage some of these features (shameless plug!).</p><h3>Design and Implementation</h3><p>In terms of making the application <em>multi-tenant aware</em>, these concepts should exist in both the <strong>database</strong> as well as the <strong>API</strong>. Some implementations add a <em>tenantId </em>column onto every tenant related table. Others will only add the column onto tables which are adjacent to the tenant model, with related models inferring tenancy from upper level models. For the purpose of simplicity, here we’ll assume that every relevant table has a <em>tenantId</em><strong><em> </em></strong>column.</p><p>Lets say that our application has 4 models:</p><ul><li>Tenant</li><li>Shop</li><li>Product</li><li>Country</li></ul><p>Tenants sign up to our application to manage their shops and products. Given this, the <strong>Tenant, Shop </strong>and <strong>Product </strong>models are tenant-aware. On top of these, each <strong>Shop</strong> has a relation to the <strong>Country</strong> model which is not tenant specific (so has no <em>tenantId </em>column).</p><h3>Retrieving data</h3><p>Most likely the <strong>GET /Tenants</strong> endpoint will be protected, since you don’t really want anyone outside of application admins getting these. With that in mind, our REST API is going to look something like:</p><pre>GET /Shops<br>GET /Products<br>GET /Countries</pre><p>Since shops and products are tenant specific, there’ll need to be a mandatory filter on the <em>tenantId:</em></p><pre>GET /Shops?tenantId=ABCD<br>GET /Products?tenantId=ABCD<br>GET /Countries</pre><p>That is about the minimal API surface we’ll need to query our entire application. I decided on <a href="http://hapijs.com/">Hapi.js</a> due to it’s recent implementation of async/await, but any API framework would be similar. An API endpoint handler would then look something like:</p><pre>// GET /Shops<br>const Model = require(&#39;./shop-objection-model&#39;);<br>async function getShops(request) {<br>  const { tenantId } = request.query;<br>  return await Model.query().where({ tenantId });<br>};</pre><p>This query results in a generated SQL query which is exactly the same as the Postgres <strong>view</strong> described earlier — slicing the shops model by tenantId.</p><pre>-- Create views for the ABCD tenant<br>CREATE VIEW “shops_view_ABCD” AS (<br>  SELECT *<br>  FROM “shops”<br>  WHERE “tenantId” = ‘ABCD’<br>)</pre><pre>CREATE VIEW “products_view_ABCD” AS (<br>  SELECT *<br>  FROM “products”<br>  WHERE “tenantId” = ‘ABCD’<br>)</pre><p>Instead of doing the SELECT into the view, we’re generating the query dynamically.</p><h4>Complex data retrieval</h4><p>It’s a very common task to ask for more related data when doing an API query. This is the foundation of <a href="http://graphql.org/learn/">Graphql</a>, to minimize the amounts of overall queries. Including related data is often referred to as eager-loading and naming will vary depending the ORM.</p><p>The objection.js framework provides a built in <a href="http://vincit.github.io/objection.js/#eager-loading">eager loading</a> function on top of queries, as long as model relationships are defined accordingly. Lets say that we want to get a bit more data, maybe shops and their associated country. An API query could look something like:</p><pre>GET /Shops?tenantId=ABCD&amp;eager=country</pre><p>This would return data in the format of:</p><pre>[{<br>  &quot;id&quot;: 1,<br>  &quot;tenantId&quot;: &quot;ABCD&quot;,<br>  &quot;name&quot;: &quot;shop 1&quot;,<br>  &quot;countryId&quot;: 10,<br>  &quot;country&quot;: {<br>   &quot;id&quot;: 10,<br>   &quot;name&quot;: &quot;New Zealand&quot;<br>  }<br> },<br> {<br>  &quot;id&quot;: 2,<br>  &quot;tenantId&quot;: &quot;ABCD&quot;,<br>  &quot;name&quot;: &quot;shop 2&quot;,<br>  &quot;countryId&quot;: 20,<br>  &quot;country&quot;: {<br>   &quot;id&quot;: 20,<br>   &quot;name&quot;: &quot;Australia&quot;<br>  }<br> }<br>]</pre><p>This ends up being a trivial implementation in the endpoint handler:</p><pre>const Model = require(&#39;./models/shop&#39;);<br>const handler = function(request) {<br>  const { tenantId, eager } = request.query;<br>  return Model<br>    .query()<br>    .where({ tenantId })<br>    .eager(eager);<br>};</pre><p>Since we’re only <em>eagering</em> in the country model, this doesn’t require any special protections. When we want to include related models which may be tenant specific then additional logic is required.</p><h4>Maintaining isolation</h4><p>With languages such as Graphql it can be more powerful to give the user flexibility when it comes to their queries. The ultimate form of flexibility would be to <strong>query any model and include any arbitrarily deep relations</strong>.</p><p>In order to do this, we need to know which models are tenant specific. This can be done with a static flag on the model definition:</p><pre>class Shop extends Model {<br>  static get isTenantSpecific() {<br>    return true;<br>  }<br>}</pre><p>The objection.js query builder then provides a <a href="http://vincit.github.io/objection.js/#context">query build hook</a> perfect for this situation. The end result will be something like “during any query or eager query, if the model is tenant specific the slice it accordingly”. The resultant handler changes slightly to become:</p><pre>const Model = require(&#39;./models/shop&#39;);<br>const handler = function(request) {<br>  const { tenantId, eager } = request.query;<br>  return Model<br>    .query()<br>    .eager(eager)<br>    .context({<br>      onBuild: builder =&gt; {<br>        if (builder._modelClass.isTenantSpecific)<br>          builder.where({ tenantId });<br>      }<br>    })<br>};</pre><p>Notice the top level <em>where({ tenantId })</em> on the model has been removed. This can now be handled by the context hook. This will result in eager queries which would be very similar to SELECTing into postgres VIEWs as shown earlier.</p><p>Now the full power of eager loading can be taken advantage of, while maintaining tenant isolation!</p><h3>Summary</h3><p>Overall a pattern to implement row-based multi-tenancy was discussed here. REST was used as a querying medium but GraphQL could equally be used with the same approach. Whether row-based multi-tenancy or some other type is preferred, the objection.js ORM provides a powerful platform for implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b73396a0ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experiences in API development on LoopbackJS]]></title>
            <link>https://medium.com/@j3y/experiences-in-api-development-on-loopbackjs-d58403b21ef8?source=rss-7404641a1056------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58403b21ef8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[loopback]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jeffrey Yan]]></dc:creator>
            <pubDate>Fri, 07 Apr 2017 20:57:35 GMT</pubDate>
            <atom:updated>2017-04-07T20:57:35.920Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapid world of javascript and node.js, you don’t really have the luxury of experimenting with frameworks before another comes up. Often I find that it’s difficult to assess the nuances of framework without diving into it for a non-trivial application — and this is and will always be the case. However the typical story is that you have a short time to do some research on available frameworks, pick one and bear the brunt of it’s maintenance throughout the application’s lifespan.</p><p>I haven’t found many user write-ups about using the <a href="https://github.com/strongloop/loopback">loopback</a> API framework for node.js. There’s some chatter about it on this <a href="https://richardcooke.info/choosing-a-restful-api-node-js-framework-koa-vs-loopback-vs-hapi/">node.js frameworks comparison</a>, as well as <a href="http://blog.pipecandy.com/chose-loop-sails-meteor/">this</a>, <a href="https://www.quora.com/Which-framework-should-I-choose-ExpressJS-or-LoopBack">this</a> and <a href="https://www.quora.com/Which-framework-should-I-choose-Sail-js-or-Loopback-by-Strongloop">this</a>. However, aside from a very high level bullet pointed pros &amp; cons list — none of these really describe characteristics of the framework that couldn’t be gleaned from just skimming over the framework documentation.</p><p>All frameworks are going to have their own pros and cons, so at the end of the day it’s more about weighing up the trade-offs that you take by selecting one and working around them. I’ll try to give my opinion on the loopback framework here and provide some insight into the trade-offs which I knew about initially as well as peculiarities discovered over time.</p><p>I’ve had some experience developing a medium sized API completely using loopback for an e-commerce style application, so some of the discussion here will be around development from that perspective. Initially I researched some node.js API frameworks but had already had experience in the past developing APIs on express. Express is a minimalistic tool, allowing devs to mould it to their liking. However in saying that, there often ends up being a lot of boilerplate and extending the application with <em>many</em> middleware packages. This leads to the first detail that drew me to loopback.</p><h3>Configuration over code</h3><p>Configuration over code is touted to reduce boilerplate and helps to establish common patterns during development. This is particularly important when working in teams. Loopback is heavily configuration driven and is sometimes referred to as <a href="http://blog.jeffdouglas.com/2015/07/07/roll-your-own-api-vs-loopback/">rails-like</a> experience and design philosophy.</p><p>The configuration driven approach is apparent immediately when defining models, which is pretty much the first step you’ll be taking when delving into the tutorials. The model configuration json definitions are powerful, allowing you to specify basic details such as model properties and types. However, other model specific details as specified on the <a href="https://loopback.io/doc/en/lb2/Model-definition-JSON-file.html">documentation</a> include:</p><pre>{<br>  &quot;name&quot;: &quot;Customer&quot;,  <em>// See Top-level properties below</em><br>  &quot;description&quot;: &quot;A Customer model representing our customers.&quot;,<br>  &quot;base&quot;: &quot;User&quot;,<br>  &quot;idInjection&quot;: <strong>false</strong>,<br>  &quot;strict&quot;: <strong>true</strong>,<br>  &quot;options&quot;: { ... }, <em>// See Options below - can also declare as top-level properties</em><br>  &quot;properties&quot;: { ... }, <em>// See Properties below</em><br>  &quot;hidden&quot;: [...], <em>// See Hidden properties below</em><br>  &quot;validations&quot;: [...],  <em>// See Validations below</em><br>  &quot;relations&quot;: {...},  <em>// See Relations below</em><br>  &quot;acls&quot;: [...],  <em>// See ACLs below</em><br>  &quot;scopes&quot;: {...},  <em>// See Scopes below</em><br>  &quot;indexes&quot; : { ...}, <em>// See Indexes below</em><br>  &quot;methods&quot;: [...],  <em>// See Methods below - New for LB2.0 - Remoting metadata</em><br>  &quot;http&quot;: {&quot;path&quot;: &quot;/foo/mypath&quot;}<br>}</pre><p>Aside from properties and relations, custom methods can be defined, ACLs to control granular permissions and access and validations to perform more detailed data validation on API calls.</p><p>All these are heavily customizable and provided out of the box when using loopback, but using <em>mixins </em>this can be extended further. <a href="https://loopback.io/doc/en/lb2/Defining-mixins.html">Mixins</a> are loopback’s plugin type design mechanism and allow extending models with some further customized functionality. Again, the typical approach to mixins is that the configuration for them is placed on the model json.</p><p>Finally, other <a href="https://loopback.io/doc/en/lb2/server-directory.html">top-level configuration</a> files are used to manage details such as:</p><ul><li>The database which particular models will reside on, and this is further extensible by allowing different environments (e.g. dev, test) to store models on differing databases</li><li>The configuration details for connecting to each database</li></ul><h3>Integrated ORM and API explorer</h3><p>You probably already guessed but loopback does come with it’s own ORM. Define a model e.g. Product, and suddenly you have ORM migration helpers for getting your tables into your SQL or NoSQL database. You’ll also have a granular REST API for this model, as well as it’s relations /api/Products, /api/Products/{id}, /api/Products/{id}/sizes.</p><p>The ORM also exposes a very powerful filtering language on the front end. You need to query <strong>products </strong>where the <strong>createdAt </strong>was last week, and include all <strong>orders </strong>which contained this product?<strong> </strong>That can all be done from the front-end REST API. The entire scope of the <a href="https://loopback.io/doc/en/lb2/Querying-data.html">filtering system</a> is defined very well, and can lead to significant progress on the front-end without too much extension on the API layer.</p><p>You’ll also have the API explorer generated which often is handled with a custom <a href="http://swagger.io/tools/">swagger</a> configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*YdGRrEdzjgKIf_KjJVbkcA.png" /></figure><p>See that text field in the top right hand corner? If any <a href="http://passportjs.org/">passport</a> compatible authentication middleware is used, then you also get authentication done almost immediately. Define some roles, ACLs and you’re well on your way to having a nice API playground where each endpoint has granular permissions.</p><p>In many cases, this is enough functionality to get you a good step of the way. You have your models defined, database configured, REST API setup and a web-based API explorer that you can share with your team. Great, <a href="https://techcrunch.com/2016/09/30/9-tricks-to-appear-smart-in-brainstorming-meetings/">ship it</a>!</p><h3>The other side of the coin</h3><p>So what’s the catch? You have all this functionality in a framework that’s backed by <a href="https://strongloop.com/">IBM StrongLoop</a> and fully compatible with the express middleware ecosystem. Surprisingly, there isn’t a <em>huge </em>amount of pain that I’ve noticed after using it for the good part of a year now. The fact that you’ve chosen loopback means that you’ve already decided to follow the <em>configuration-over-code</em> mantra.</p><p>You’re happy to spend significantly less time developing and establishing common code organization patterns, and fitting into the structures that are suggested by the framework. There’s a good sized community, a large number of github stars and a <a href="http://gitter.im/strongloop/loopback">gitter</a> room where you’ll usually get a response within a day or less.</p><p>The first major pain point I’ve noticed is the ORM limitations which have been heavily documented in <a href="https://github.com/strongloop/loopback/issues/517">github issue #517</a> — you can’t filter a target model by it’s related model properties. An example of this in e-commerce could be that you have a list of product categories that the user is browsing through, something like <em>books, clothing </em>and <em>electronics</em>. Each of these categories has it’s own set of products (<em>category </em>hasMany <em>product).</em></p><p>Now you want to find all categories which have a product under $10. Alternatively, you might want to find all products with a category which starts with the letter <em>A. </em>This kind of search isn’t currently possible on the loopback ORM filtering implementation. Often, you find that you end up writing custom SQL for this case.</p><pre>SELECT DISTINCT id FROM category</pre><pre>INNER JOIN product ON product.categoryid = category.id</pre><pre>WHERE product.price &lt; 10</pre><p>This isn’t ideal, especially since this a trivial example. Often you’ll need to query a model by relations which are multiple levels deep. Furthermore, when you use raw SQL queries you’ll lose the validation and nice attribute mappings that the convenience of using an ORM provides.</p><p>The non-existent <strong>filtering on related model properties</strong> has definitely been the biggest issue for me during development, and if it were available today then I think it could sway many decisions during framework research. It may not be a deal breaker for many applications, and the filtering language in general is extremely powerful out of the box. Before you start development, have a good idea of the types of queries that you’ll want to be doing on your data. Often the fact that SQL was the database dialect of choice can be due to <em>not knowing what queries you’ll be doing later.</em></p><p>The next minor issue is the <a href="https://loopback.io/doc/en/lb2/Using-current-context.html">loopback context</a> dilemma. This is to do with context propagation during an API request.</p><blockquote>The current implementation of loopback-context is based on the module <a href="https://www.npmjs.com/package/continuation-local-storage">continuation-local-storage</a> which is known to have many problems, (for example, see <a href="https://github.com/othiym23/node-continuation-local-storage/issues/59">issue #59</a>). As a result, loopback-context does not work in many situations, as can be seen from issues reported in LoopBack’s <a href="https://github.com/strongloop/loopback/issues?utf8=%E2%9C%93&amp;q=is%3Aissue%20getCurrentContext">issue tracker</a>.</blockquote><p>Typically when an application is developed in an <em>express style</em> structure, you’ll have access to the req and res objects to read from request parameters as well as control the response output. These objects are propagated throughout middleware, and are usually assumed to be accessible.</p><p>Loopback instead <a href="https://groups.google.com/d/msg/loopbackjs/zPBnpxuzx5o/D-0hYmoXj6MJ">separates the application into distinct layers</a>, which allows the <em>remoting</em> layer to be independent of the <em>persistence </em>layer. This allows the remoting layer to be implemented with a medium other than HTTP, and the persistence layer to be implemented with any database connector. However, maintaining context propagation between layers is an issue in this type of design.</p><p>A situation this could arise is that you want to <a href="https://loopback.io/doc/en/lb2/Operation-hooks.html">add an observer </a>on a <em>Product</em> modification, so that you can keep track of who modified it.</p><pre>Product.observe(&#39;before save&#39;, <strong>function</strong>(ctx, next) {<br>  //Read the user id here, and store it during every save<br>  ...<br>});</pre><p>Unfortunately, the user ID often exists as a property which exists on the request context (maybe within a JWT). None of the request context will be available within this operation hook. Instead, you’ll have to override beforeRemote calls to achieve a similar result. This has been documented in a <a href="https://github.com/strongloop/loopback/issues/1495">workaround</a>, but is not as clean as having access to it directly. Especially as this part of the <a href="https://loopback.io/doc/en/lb2/Operation-hooks.html#access">documentation</a> which still uses the context (which it shouldn’t be, since it has been discouraged).</p><pre>MyModel.observe(&#39;access&#39;, <strong>function</strong> limitToTenant(ctx, next) {<br>  ctx.query.where.tenantId <strong>=</strong> loopback.getCurrentContext().tenantId;<br>  next();<br>});</pre><h3>Conclusions</h3><p>Overall my experience with loopback has been mainly positive bar those 2 experiences I detailed above. The framework is a solid choice for anyone developing an API on node, particularly since it’s compatible with the huge range of existing express middleware. Also of note is that StrongLoop is now the maintainer for the express respository and they’ve done a great job of pushing out minor loopback updates regularly.</p><p>Hopefully I’ve given some insight into the trade-offs when using loopback, which can be used to compare against another framework in consideration. As I stated earlier, every framework is going to have it’s pros and cons. It’s always going to be about weighing up which of these are more important to the project at hand, then developing your way around missing features. Always have a positive outlook and keep in mind, there’s no <em>wrong</em> decision when it comes to development, just various levels of right!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58403b21ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics with React-Redux SPAs and Google Tag Manager — Part 2]]></title>
            <link>https://medium.com/@j3y/analytics-with-react-redux-spas-and-google-tag-manager-part-2-1c05aef3d954?source=rss-7404641a1056------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c05aef3d954</guid>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Jeffrey Yan]]></dc:creator>
            <pubDate>Sat, 24 Sep 2016 21:05:29 GMT</pubDate>
            <atom:updated>2016-09-24T21:05:29.623Z</atom:updated>
            <content:encoded><![CDATA[<p>I wrote about <a href="https://medium.com/@j3y/analytics-with-react-redux-spas-and-google-tag-manager-4d3a55833619#.ysnn36k8c">my experiences applying analytics to React-Redux applications in Part 1</a>, which showed the initial setup process. To reiterate on that, the goals that I had were:</p><ol><li>Flexibility — adding new insights without code redeployment</li><li>Ease of use — potentially allowing less tech-savvy people to add their own insights</li></ol><p>Most methods which I read about involved sending specifically formatted data payloads to the analytics platform, or sending every redux event — both of which weren’t ideal.</p><p>I found that the combination of <a href="https://www.google.co.nz/analytics/tag-manager/">Google Tag Manager</a> and <a href="https://mixpanel.com/">Mixpanel</a> suited my needs the best.</p><ul><li>Google Tag Manager acts as the event consumption source, allowing some data reformatting before sending to analytics</li><li>Mixpanel allowed a <em>NoSQL’ish</em> approach to analytics which I liked with a send-first tweak-later approach. This flexible approach caters well to events and data formats which can change rapidly during development.</li></ul><p>In this second post, I’ll discuss some of the experiences I’ve had integrating analytics in React-Redux in some more depth. These specific aspects seem to be tightly coupled between development and analytics, and implementing them from the beginning can save a lot of headache later on:</p><ol><li>Page views</li><li>User identity</li><li>CRUD</li></ol><h3>Page Views</h3><p>Part 1 discussed the initial implementation of page views with a single-page app, specifically tracking the initial landing and subsequent page views. These page views can easily be enriched with convenience data including <em>page name </em>and <em>object instance IDs</em>, both of which can be a huge help when quickly generating reports.</p><p>The base page view tag looks something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8Pp8urqx9ru4i3EpRBsAPw.png" /><figcaption>Basic page view tag structure</figcaption></figure><p>This tag triggers on both the intial page load, as well as subsequent browser history changes triggered by the javascript framework’s router. The custom HTML script then simply triggers <strong>mixpanel.track(‘</strong>Page View<strong>’)</strong>.</p><h4>Page Names</h4><p>At the beginning of a project it’s convenient to set up some convenient page names, so that within analytics you can filter by something like <strong>Page Name is equal to “User Profile” </strong>— although this is purely for convenience. You can skip this section if the page title field is diligently populated by the application.</p><p>Create a new variable called <strong>Page.name</strong>, set up with a custom javascript type. Variables that execute custom javascript are in the form of a function:</p><pre>function() {<br>  var PAGE_MAP = {<br>    &#39;User Profile&#39;: /^\/userprofile$/,<br>    &#39;Todos Page&#39;: /^\/todos$/,<br>    &#39;View Todo&#39;: /^\/todos/\d+$/<br>  };</pre><pre>  for (var i = 0; i &lt; Object.keys(PAGE_MAP).length; i++)<br>    if (PAGE_MAP[key].test(window.location.pathname))<br>      return key;</pre><pre>  return &#39;&#39;;<br>}</pre><p>This variable can then be accessed from within the <strong>Page View</strong> tag. Now the analytics event can look like:</p><pre>mixpanel.track(&#39;Page View&#39;, {<br>  &#39;Page Name&#39;: {{Page.name}}<br>});</pre><h4>Object Identifiers</h4><p>Often in an application there are multiple identifiers that can be used throughout to determine the<strong> current context</strong>. For example, maybe you have a list of Todos that are editable. When you open each todo, the URL would look something like:</p><pre>http://my-app/todos/123</pre><p>This is particularly easy to handle if you already have it set up within the routing of the application. In the same <strong>Page View</strong> tag, some code can be used to tag every other event that occurs on this page:</p><pre>// Append the todo ID if it exist<br>var todoIdMatch = document.location.pathname.match(/^\/todos\/(\d+)$/);<br>if (todoIdMatch)<br>  mixpanel.register({todoId: todoIdMatch[1]});<br>else<br>  mixpanel.unregister(&#39;todoId&#39;);</pre><pre>mixpanel.track(&#39;Page View&#39;, {<br>  &#39;Page Name&#39;: {{Page.name}}<br>});</pre><p>Using <strong>mixpanel.register </strong>will result in every subsequent event sent to have the todoId property. If you later decide to send a <strong>Button Clicked</strong> event from this URL, you’ll know exactly which todo ID this event refers to. If the page does not match the path style <strong>/todos/123</strong> then <strong>mixpanel.unregister</strong> will remove this property.</p><p>This is also appropriate for nested data types, for example if todos are contained within groups and the URL looks something like:</p><pre>http://my-app/groups/234/todos/123</pre><p>The same pattern can be applied in this case, tracking both the parent <strong>groupId </strong>and the child <strong>todoId.</strong></p><h3>User Identity</h3><p>In <a href="https://medium.com/@j3y/analytics-with-react-redux-spas-and-google-tag-manager-4d3a55833619#.mllfkp7p5">part-1</a> I briefly discussed tracking user identity, and this was particularly easy if a redux authentication flow was already built into the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*AsTRQ6i26y22HVgqD8a6uw.png" /><figcaption>A basic tag tracking a user ID after the redux AUTHENTICATE event</figcaption></figure><p>Mixpanel also lets you set additional user identity properties after the user has been identified. For example, in the <strong>page view</strong> tag another snippet of code can be added to track the total number of page views for this user:</p><pre>mixpanel.people.increment(&#39;Total Page Views&#39;)</pre><p>Furthermore, additional properties received from later events can also be set on the identity object. For example if social data is retrieved with a separate API call from the base user data:</p><pre>mixpanel.people.set({&#39;Facebook ID&#39;: &#39;12345&#39;})</pre><h3>CRUD</h3><p>A large number of applications are fundamentally a set of <strong>CRUD </strong>(create-read-update-delete) operations. For our example ToDo app, the user would <strong>create</strong> a todo, then <strong>update </strong>it by editing its details, then later possibly <strong>delete </strong>it after it’s completion. These operations are accompanied by the typical GET/POST/PUT/DELETE http calls to the REST API.</p><p>The <a href="http://redux.js.org/docs/advanced/AsyncActions.html">redux async actions flow</a> encapsulates this pattern with each action as 3 distinct events (REQUEST, SUCCESS and FAILURE). For an action to create a todo the corresponding redux actions would be named something along the lines of:</p><pre>CREATE_TODO_REQUEST<br>CREATE_TODO_SUCCESS<br>CREATE_TODO_FAILURE</pre><p>Since each of these events has already been sent to the Google Tag Manager dataLayer, they can be immediately consumed and sent to analytics. A simplifed <em>createTodo </em>redux action would look something like:</p><pre>function createTodo(todo) {<br>  return dispatch =&gt; {<br>    dispatch({type: <strong>CREATE_TODO_REQUEST</strong>});</pre><pre>fetch(`${API_URL}/todos`, {<br>      method: &#39;post&#39;,<br>      body: JSON.stringify(todo)<br>    })<br>      .then(res =&gt; res.json())<br>      .then(json =&gt; dispatch({<br>        type: <strong>CREATE_TODO_SUCCESS</strong>,<br>        payload: todo<br>      }))<br>      .catch(err =&gt; dispatch({<br>        type: <strong>CREATE_TODO_FAILURE</strong>,<br>        payload: err<br>      }));<br>  } <br>}</pre><p>To create an analytics event to track a CRUD style event such as <strong>Create ToDo</strong>, the following sequence should be followed:</p><ol><li>Create the trigger</li><li>Create a variable for each attribute that is required to be sent to analytics (regardless if it is nested data)</li><li>Create the tag and send the data</li></ol><p>Notice this pattern is similar for other events such as tracking user identity, and it is typically the most efficient method in Google Tag Manager of tracking generic events without any modifications to the codebase.</p><h4>1. Create the trigger</h4><p>Before you start, I’d recommend creating a folder to store related triggers/variables/tags as they can quickly grow in number and it’s easy to lose track of them. First, create a trigger and select the custom event option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*rFSkeeMVyyoZzrKOX5PgPQ.png" /><figcaption>Create a new custom event for this action</figcaption></figure><p>Give the event name the same name as the redux event, and give the trigger name at the top something easily recognisable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*H0QHTyBngpYOtsUVKjHSbg.png" /><figcaption>Add the redux event name as the tag manager event name</figcaption></figure><h4>2. Create the variables</h4><p>Variables need to be created for each property that is required to be tracked. The content of a todo redux action may look something like the following:</p><pre>{<br>  type: CREATE_TODO_SUCCESS,<br>  payload: {<br>    id: 123,<br>    name: &#39;Buy Groceries&#39;,<br>    description: &#39;Remember we need milk&#39;<br>  }<br>}</pre><p>Each of the payload properties is desirable for tracking, thus a variable must be created for each — since Google Tag Manager does not allow object property access using something like dot notation. For the <em>name </em>property, create a new variable with the <em>Data Layer Variable</em> type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*TpqSNTNt-ZBNDvuPUc0zCw.png" /><figcaption>Select the Data Layer Variable type</figcaption></figure><p>For the variable name, dot notation can be used. To access the “name” field of the redux action, the dot notation <strong>payload.name </strong>would be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*HJGv9OqyhcQoUG8vGsNmRA.png" /><figcaption>The variable name</figcaption></figure><p>For top level attributes (e.g. attributes immediately under the <strong>payload</strong>) I usually just give it a variable name of <strong>Event.VARIABLE_NAME, </strong>e.g Event.name, Event.id, Event.message and whatever else you need at the top level. These variables can then be reused for other events with the same top level properties.</p><p>For nested properties, the pattern is similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*s8rPhGVpw632lfCFizQq5g.png" /></figure><h4>3. Create the tag</h4><p>Finally, once the trigger and the variables have been set up, it is time send this data to the analytics platform. Set up a new tag to trigger on the successful todo creation from previously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*-FfRX7YH9Fg3LJ9JqXmb8g.png" /><figcaption>The full todo created tag</figcaption></figure><p>A similar pattern can be done for the other CRUD events, eventually resulting in ridiculously easy analytics such as a funnel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*X-mZ2p28LSHZgnaD3-q9CA.png" /><figcaption>A funnel tracking which visitors eventually created a todo</figcaption></figure><h3>Conclusions</h3><p>I’ve found this style of development allows your analytics to evolve along with your application development. A huge benefit is that it’s essentially codeless, and you keep the codebase clean plus remove the need to redeploy during every analytics update. If someday in the future, Google Tag Manager allows nested access to Data Layer variables then it will become significantly easier to create and track events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c05aef3d954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics with React-Redux SPAs and Google Tag Manager]]></title>
            <link>https://medium.com/@j3y/analytics-with-react-redux-spas-and-google-tag-manager-4d3a55833619?source=rss-7404641a1056------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d3a55833619</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <dc:creator><![CDATA[Jeffrey Yan]]></dc:creator>
            <pubDate>Tue, 13 Sep 2016 04:46:47 GMT</pubDate>
            <atom:updated>2017-04-27T20:07:52.723Z</atom:updated>
            <content:encoded><![CDATA[<p>React-Redux has become a hugely popular web development combo, but I’ve found that there aren’t too many guides out there on how to sprinkle in analytics. Most implementations I’ve seen require some modification to your app’s code, often with analytics specific business logic.</p><p>The most common pattern seems to be with redux middleware, which definitely is a step in the right direction. The redux-analytics package encompasses this pattern nicely. Every redux action becomes a place where insights can be extracted, simply by appending some analytics information to the action metadata.</p><pre>const action = {<br>  type: &#39;MY_ACTION&#39;,<br>  meta: {<br>    analytics: {<br>      type: &#39;my-analytics-event&#39;,<br>      payload: {<br>        some: &#39;data&#39;,<br>        more: &#39;stuff&#39;<br>      }<br>    }<br>  }<br>};</pre><p>This is a great start, and I had many of these analytics payloads throughout the codebase for a while and it worked great. The problem was that whenever someone wanted to change pretty much anything, it required a redeployment. Plus you’ll often have less tech savvy users wanting to add their own insights.</p><p>We already had an integration with <a href="https://developers.google.com/tag-manager/quickstart">Google Tag Manager</a> (gtm.js), so I was a little biased towards this implementation. This goes two-fold for other departments who were already familiar with gtm.js, which is currently reaping it’s benefits with less development overhead when adding analytics insights.</p><p>Anyway lets get started on a basic Redux integration with gtm.js and my personal analytics platform of choice — <a href="https://mixpanel.com/">Mixpanel</a>.</p><h3>Getting Started</h3><p>If you’re not already familiar with gtm.js, you can simply inject it’s javascript snippet into your app then get going. All of the configuration is driven through the gtm web UI, which has come a long way in the years.</p><p>Now on the app side, the <a href="http://redux.js.org/docs/advanced/Middleware.html">Redux middleware</a> approach is still the way to go here:</p><pre>const analytics = () =&gt; next =&gt; action =&gt; {<br>  window.dataLayer = window.dataLayer || [];<br>  dataLayer.push({<br>    event: action.type,<br>    payload: action.payload<br>  });<br>  return next(action);<br>};</pre><pre>// Add in the analytics middleware<br>let store = createStore(<br>  todoApp,<br>  applyMiddleware(<br>    analytics,<br>    thunk,<br>  )<br>);</pre><p>Instead of dispatching analytics events from the application, it’s now firing everything to the gtm.js <a href="https://developers.google.com/tag-manager/devguide#datalayer">dataLayer</a>. Each dataLayer event needs an <em>event </em>attribute to denote the type of event, but other than that you can structure your data format in any way that suits your application.</p><p>Now that’s pretty much it for the initial setup, assuming you already have the <a href="https://developers.google.com/tag-manager/quickstart">gtm.js snippet</a> embedded in your application somewhere. Everything else can now be driven by the Tag Manager UI. I’ve started storing tags/triggers/variables in their own respective folders, but these can be changed at any time.</p><h3>Creating the first event</h3><p>To get started, lets setup the beloved <em>page load</em> events that management always seems to want. A typical React SPA usually has some form of client-side routing, so there needs to be a method to track the initial page view (landing) and route transitions. To capture both of these, 2 triggers are required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*BOFt20TFuxJag0zGlf5dTQ.png" /><figcaption>Create the trigger in some folder of your choice</figcaption></figure><p>First, create the tag for the page load. I used the <em>window loaded </em>trigger here, and named it <em>Global.pageLoad </em>for use later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*h7YthEpvHzjzqIsoZMWtHw.png" /><figcaption>Create the first pageLoad event</figcaption></figure><p>Next, create the history change event, which will capture route transitions from your SPA router (e.g. react-router). This is similar to the <em>Window Loaded</em> event above, but the <em>History Change</em> trigger can be selected instead.</p><p>Create a new tag <em>Page View</em> that triggers on either of these. I’ll be using Mixpanel throughout, but the same can apply to Google Analytics or your platform of choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*8Pp8urqx9ru4i3EpRBsAPw.png" /></figure><h3>Tracking authentication</h3><p>The place where Mixpanel shines is tracking arbitrary events, with arbitrary (and sometimes changing) event attributes. This is the perfect behavior for a dynamic web application, and especially for the range of redux events that are fired.</p><p>In many applications, there’ll be some kind of <em>authentication</em> event fired. In my current app it’s structured as follows:</p><pre>const authenticateAction = {<br>  type: &#39;AUTHENTICATE&#39;,<br>  payload: {<br>    user,<br>    token<br>  }<br>}</pre><h4>1. Create the trigger</h4><p>This event is now available to use in Tag Manager as a custom event. Create a new trigger referencing this authenticate action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*EdJ9TN-OtbWi29677rtpJA.png" /><figcaption>The Event name should match the string type field in the redux action</figcaption></figure><h4>2. Access the data</h4><p>To access variables within your redux events, you need to create a Tag Manager variable for each primitive you want to access. Unfortunately there is no object dot notation access (yet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*Fk8MH75wqf6f7DeGEaFLWw.png" /><figcaption>Access the user id variable within the redux action</figcaption></figure><h4>3. Send the analytics event</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*rC0KI9kSFdDZnSzn4H2lOw.png" /><figcaption>The complete authentication tag</figcaption></figure><p>Now that we have the trigger, and the data, we can send an analytics event. For user identity, this often varies per analytics-platform.</p><p>Create a new <em>tag</em> that uses the previous <em>AUTHENTICATE </em>event, along with the <em>User.id </em>variable. Inside a <em>Custom HTML</em> tag, the variable can be accessed using the <strong>{{VARIABLE}}</strong> notation.</p><h3>Conclusion</h3><p>That’s all there is to it to get started, now try login to your application and you’ll see the identification action get triggered and sent to your analytics. Now your analytics platform can grow as your application grows, without littering the code base with metadata tags.</p><p>It’s just as easy to add other actions and variables, and create triggers that fire conditionally based on the value of a variable — all within Tag Manager.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d3a55833619" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>