<?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 Michael Chan on Medium]]></title>
        <description><![CDATA[Stories by Michael Chan on Medium]]></description>
        <link>https://medium.com/@michaelchan-13570?source=rss-d82560d346a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*AOdOVPvfmVDdIgH0qPZIXQ.jpeg</url>
            <title>Stories by Michael Chan on Medium</title>
            <link>https://medium.com/@michaelchan-13570?source=rss-d82560d346a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:35:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelchan-13570/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[Build a web-scraped time-series application with AWS CDK in TypeScript — Part 4.2]]></title>
            <link>https://michaelchan-13570.medium.com/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-4-2-951eae99480d?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/951eae99480d</guid>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 03:11:09 GMT</pubDate>
            <atom:updated>2020-11-05T03:11:09.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a web-scraped time-series application with AWS CDK in TypeScript — Part 4.2</h3><h4>Build scrapers with CDK: Create our scraper</h4><p><a href="https://medium.com/p/8eb5895d9a85">Previous: Part 4.1. Build scrapers with CDK: Setup bundling with webpack and create our first lambda in TypeScript</a></p><p>It’s time to start scraping!</p><p><em>[DISCLAIMER] </em>This project will focus on building web-scrapers with TypesScript (or more accruately JavaScript). I know it is more usual to do that in other languages like Python, but that’s why I would like to dig into the possibility and difficulties of using JavaScript.</p><h3>Create the record type</h3><p>First, let’s create our IndexPriceRecord type <a href="https://medium.com/p/adbbbcf01b68">drafted in previous section:</a></p><pre>// src/models/IndexPriceRecord.type.ts</pre><pre>interface IndexPriceRecord {<br>   symbol: string; // Basically an ID<br>   name: string;<br>   lastPrice: number;<br>   change: number;<br>   changeRate: number; // in %<br>   time: string; // Let&#39;s use ISOTimestamp<br>}<br>export default IndexPriceRecord</pre><h3>Create the scraper</h3><p>We will use the helper from the library <strong>simply-utils</strong>, which does the Puppeteer chromnium instance launching work for us and let us focus on the scraping logic.</p><pre>// src/services/cron/handlers/scrape.ts</pre><pre>import { ScheduledHandler } from &#39;aws-lambda&#39;<br>import launchPuppeteerBrowserSession<strong>,</strong> { GetDataWithPage } from &#39;simply-utils/dist/scraping/launchPuppeteerBrowserSession&#39;<br>import IndexPriceRecord from &#39;src/models/IndexPriceRecord.type&#39;</pre><pre>const getDataFromPage: GetDataWithPage&lt;IndexPriceRecord[]&gt; = async page =&gt; {<br>  // Our scraping logic goes here<br>}</pre><pre>export const handler: ScheduledHandler = async () =&gt; {<br>  const results = await launchPuppeteerBrowserSession([getDataFromPage])<br>  console.log(JSON.stringify(results<strong>,</strong> null<strong>,</strong> 2))<br>}</pre><p>What the launchPuppeteerBrowserSession does is initiating the chromnium instance using the chrome-aws-lambda library and return a puppeteer.Page object for us. <a href="https://github.com/puppeteer/puppeteer">The page object</a> is like a cursor of which page you are on in the browser session. You can use it to navigate between different pages then.</p><p>So what we need to do is just returning our scraped records from the getDataFromPage function. launchPuppeteerBrowserSession accepts an array of that kind of functions and then it returned the results array with the same sequence.</p><h4>Our Scraping Logic with the DOM</h4><p>We have to utilize the page object in our getDataFromPage:</p><pre>// src/services/cron/handlers/scrape.ts<br>...<br>const PAGE_URL = &#39;https://finance.yahoo.com/world-indices/&#39;<br>const getDataFromPage: GetDataWithPage&lt;IndexPriceRecord[]&gt; = async page =&gt; {<br><strong>  // Navigate to the page we want to scrape<br></strong>  await page.goto(PAGE_URL)<br> <strong> // Wait for some element to be rendered completely</strong><br>  await page.<em>waitForSelector</em>(&#39;.yfinlist-table &gt; tbody &gt; tr:last-child &gt; td:last-child&#39;)<br>  return page.evaluate((): IndexPriceRecord[] =&gt; {<br>    // Perform normal DOM query like on normal browser <br>  })<br>}<br>...</pre><p>Here we first navigate to the page we want to scrape. Then we have to <strong>wait for the last cell of the table element to be rendered</strong>, as there might be chance the elements are rendered by JavaScript.</p><p>Okay, let’s finally hook up our scraping logic:</p><pre>return page.evaluate((): IndexPriceRecord[] =&gt; {<br>  const tableRows: NodeListOf&lt;HTMLTableRowElement&gt; = document<br>    .querySelectorAll(&#39;.yfinlist-table &gt; tbody &gt; tr&#39;)<br>  <strong>/**<br>   * We have to put this inside the<br>   * callback function of page.evaluate,<br>   * because it need to be in the virtual client-side scope.<br>   */</strong><br>  const parseNum = (text: string): number =&gt; parseFloat(text.replace(/\+|,|%/g<strong>,</strong> &#39;&#39;))</pre><pre>  return Array.from(tableRows).map(tableRow =&gt; {<br><strong>    // Tell typescript that it is a list of data cells<br></strong>    const cols = tableRow.children as HTMLCollectionOf&lt;HTMLTableDataCellElement&gt;<br>    const symbol = cols[0].innerText<br>    const name = cols[1].innerText<br>    const lastPrice = parseNum(cols[2].innerText)<br>    const change = parseNum(cols[3].innerText)<br>    const changeRate = parseNum(cols[4].innerText)<br>    const time = <strong>new</strong> Date().toISOString()</pre><pre>    return {<br>      symbol<strong>,<br>      </strong>name<strong>,<br>      </strong>lastPrice<strong>,<br>      </strong>change<strong>,<br>      </strong>changeRate<strong>,<br>      </strong>time<strong>,<br>    </strong>}  })<br>})</pre><p>Now you should be able to scrape an array of IndexPriceRecord items!</p><p>Next: Part 5. Create the create-table / update-table handler <strong>(COMING SOON)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951eae99480d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Web-Scraped Time-Series Application With AWS CDK in TypeScript — Part 4.1]]></title>
            <link>https://medium.com/swlh/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-4-1-8eb5895d9a85?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb5895d9a85</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[puppeteer]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 03:09:54 GMT</pubDate>
            <atom:updated>2020-11-17T20:35:42.345Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Web-Scraped Time-Series Application With AWS CDK in TypeScript — Part 4.1</h3><h4>Build scrapers with CDK: Setup bundling with webpack and create our first lambda in TypeScript</h4><p><a href="https://medium.com/p/9992b072f504">Previous: Part 3. The setup of CDK project and structure</a></p><p>Okay, now it’s time to setup bundling and create a lambda!</p><h3>Configure .gitignore (if you use git)</h3><p>You might need to add the following lines to the .gitignore file if you use git:</p><pre># Ignore webpack config<br>!webpack.config.js</pre><pre># Ignore build and bundles<br>build<br>bundles</pre><pre># Ignore template.yaml<br>template.yaml</pre><h3>Configure TypeScript Build</h3><p>Let’s configure our tsconfig.json to tell TypeScript the I/O directories of build. Let’s add/modify the following lines in the tsconfig.json :</p><pre>&quot;compilerOptions&quot;: {<br>    &quot;rootDir&quot;<strong>:</strong> &quot;src&quot;<strong>,<br>    </strong>&quot;outDir&quot;<strong>:</strong> &quot;build&quot;<br>},<br>&quot;exclude&quot;<strong>:</strong> [&quot;node_modules&quot;<strong>,</strong> &quot;cdk.out&quot;]<strong>,<br></strong>&quot;include&quot;<strong>:</strong> [&quot;src&quot;]</pre><p>Now if you run npm run build or yarn build (which is essentially running tsc ), you should notice some build files added in the <strong>/build </strong>directory<strong>.</strong></p><p>If you want to use absolute import path later, please keep the&quot;baseUrl&quot; as &quot;./&quot; because we will need the src keyword in the path for webpack to map. That means you will need to import like from &quot;src/api/helpers/someHelpers&quot; . That’s a bit trade-off though.</p><h3>Configure webpack bundling</h3><p>Create a webpack.config.js file in at project root and add the following to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54cbee0eb32d261a10175208b4c54faa/href">https://medium.com/media/54cbee0eb32d261a10175208b4c54faa/href</a></iframe><p>What the above configuration does is to:</p><ol><li>Read and create a config object for each /handler folder of each of the “service” under the /build/services directory</li><li>For each config it does sort of things like <em>mapping the filenames, replacing “src” in import paths with “build”, bundling chromnium executable etc.</em></li></ol><p>Before testing our setup, let’s create a dummy handler file (otherwise it won’t work), for each service:</p><pre>// src/services/api/handlers/dummyHandlers.ts<br>// src/services/cron/handlers/dummyHandlers.ts</pre><pre>export const handler = (): void =&gt; {<br>  console.log(&#39;Dummy handler&#39;)<br>}</pre><p>Also, let’s add the webpack script to the package.json :</p><pre>&quot;build&quot;<strong>:</strong> &quot;tsc &amp;&amp; webpack&quot;</pre><p>Now if you run npm run build or yarn build , you should see the following files in the /bundles folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*NNMzqwnJ9qcVwCu2r56UMw.png" /><figcaption>Testing webpack bundling setup</figcaption></figure><p>Done! We can later reference these files as lambda source code like bundles/cron/handlers/dummyHandler . Note that the bundler_report.html files are just for bundle analyzing purpose, which will not be covered but you might use it to optimize your bundle sizes later.</p><h3>Create Our First lambda</h3><p>Let’s first rename the dummyHandler.ts under /cron toscrape.ts so not to confuse with the other.</p><p>Next, let’s create our basic skeleton of the handler:</p><pre><strong>// src/services/cron/handlers/scrape.ts</strong></pre><pre>import { ScheduledHandler } from &#39;aws-lambda&#39;</pre><pre>export const handler: ScheduledHandler = () =&gt; {<br>  console.log(&#39;I am running!&#39;)<br>}</pre><p>Let’s setup our CDK construct in the cron.ts so that we can alsodebug our scrape.ts lambda later:</p><ol><li>Create the IAM role for the lambda:</li></ol><pre><strong>// src/services/cron/cron.ts</strong></pre><pre>import * as cdk from &#39;@aws-cdk/core&#39;<br>import * as iam from &#39;@aws-cdk/aws-iam&#39;<br>...<br>const ROLE_ID = &#39;CronRole&#39;<br>...<br>const constructIamRole = (scope: cdk.Construct): iam.Role =&gt; {<br>  const role = <strong>new</strong> iam.Role(scope<strong>,</strong> ROLE_ID<strong>,</strong> {<br>    assumedBy<strong>:</strong> <strong>new</strong> iam.ServicePrincipal(&#39;lambda.amazonaws.com&#39;)<strong>,<br>  </strong>})<br>  return role<br>}<br>...</pre><p>2. Create the lambda:</p><pre><strong>// src/services/cron/cron.ts<br>...<br></strong>import * as lambda from &#39;@aws-cdk/aws-lambda&#39;<br>...<br>const constructLambdas = (scope: cdk.Construct<strong>,</strong> role: iam.Role) =&gt; {<br>  <strong>new</strong> lambda.Function(scope<strong>,</strong> &#39;Scrape&#39;<strong>,</strong> {<br>    code<strong>:</strong> lambda.Code<br>      .fromAsset(`bundles/${SERVICE_PATHNAME}/handlers`)<strong>,<br>    </strong>handler<strong>:</strong> &#39;scrape.handler&#39;<strong>,<br>    </strong>timeout<strong>:</strong> cdk.Duration.minutes(TIMEOUT_MINS)<strong>,<br>    </strong>runtime<strong>:</strong> lambda.Runtime.NODEJS_12_X<strong>,<br>    </strong>memorySize<strong>:</strong> SCRAPER_MEMORY_SIZE_MB<strong>,<br>    </strong>role<strong>,<br>  </strong>})<br>}<br>...</pre><p>3. Put all things together in the construct function:</p><pre><strong>// src/services/cron/cron.ts</strong></pre><pre>...<br>function construct (scope: cdk.Construct): void {<br>  const role = constructIamRole(scope)<br>  constructLambdas(scope<strong>,</strong> role)<br>}<br>export default { construct }</pre><h3>Test the lambda locally</h3><ol><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">Install the SAM CLI</a></li><li>Add the following scripts to the package.json</li></ol><pre>&quot;template&quot;<strong>:</strong> &quot;npm run build &amp;&amp; cdk synth --no-staging &gt; template.yaml&quot;<strong>,<br></strong>&quot;invoke&quot;<strong>:</strong> &quot;npm run template &amp;&amp; sam local invoke&quot;<strong>,</strong></pre><p>3. Run the followings npm run template or yarn template to create a template.yaml file at the project root. You can then find the lambda resource ID by search “scrape”, and you will find something like scrape&lt;Unique ID&gt; under the Resources<strong>: </strong>property and above a line like Type<strong>:</strong> AWS::Lambda::Function . <strong>This step is only required when you first run your function, in order to get the resource ID.</strong></p><p>4. Then run npm run invoke scrape&lt;Unique Id&gt; . You should have got the output like this:</p><pre>Invoking scrape.handler (nodejs12.x)<br>Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-nodejs12.x:rapid-1.6.2.</pre><pre>Mounting &lt;USER_DIR&gt;/world-indices-monitor-backend/bundles/cron/handlers as /var/task:ro,delegated inside runtime container<br>START RequestId: &lt;SOME_ID&gt; Version: $LATEST<br><strong>2020-10-28T09:15:07.493Z        &lt;SOME_ID&gt;   INFO    I am running!<br></strong>END RequestId: &lt;SOME_ID&gt;<br>REPORT RequestId: &lt;SOME_ID&gt; Init Duration: 120.76 ms        Duration: 8.41 ms     Billed Duration: 100 ms  Memory Size: 700 MB     Max Memory Used: 41 MB</pre><pre>null</pre><p>If you are not able run and get some errors like:</p><pre>Error: Failed to parse template: mapping values are not allowed here<br>  in &quot;&lt;unicode string&gt;&quot;, line 2, column 7:<br>      node: ConstructNode {<br>          ^</pre><p>Chances are the template.yaml contains some invalid content (like the JavaScript context object), because something has been printed during the CDK synthesis process. You can probably fix by <strong>removing any </strong><strong>console.log inside any CDK construct script file</strong>.</p><h3>Deploy and test the lambda on AWS console</h3><p>Add the following script to package.json:</p><pre>&quot;deploy&quot;: &quot;cdk deploy WorldIndicesMonitorBackendStack --require-approval never&quot;</pre><p>Then run npm run deploy , it should be able to deploy and be viewed on the AWS console. Note that the argument--require-approval never is just a handy way to bypass some inquiries from the CLI during the deploy process. Feel free to remove it if you don’t need.</p><h4>Configure AWS Profile</h4><p>By default, any cdk command uses the <strong>default profile. </strong>If you want to run cdk script with a different profile, you can follow <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html">this guide</a> to configure you default profile or other profiles. You can append --profile=&lt;profile name&gt; after the cdk script like:</p><pre>&quot;deploy&quot;: &quot;cdk deploy --profile=&lt;profile name&gt; WorldIndicesMonitorBackendStack --require-approval never&quot;</pre><h4>Boostraping Assets</h4><p><strong>If this is your first deploy using CDK with asset code, you might probably got the following error after you run the deploy script:</strong></p><pre>❌  WorldIndicesMonitorBackendStack failed: Error: This stack uses assets, so the toolkit stack must be deployed to the environment (Run &quot;cdk bootstrap aws://unknown-account/unknown-region&quot;)</pre><p>This is because a CDK toolkit stack is required by AWS to do <a href="https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html">boostraping</a>. To solve this, run the following command:</p><pre>cdk bootstrap ://unknown-account/unknown-region</pre><p>Then it should work by running the deploy script again!</p><p>Now you should see your stack on the CloudFormation console and also you can test you lambda on the console too!</p><p><a href="https://medium.com/p/951eae99480d">Next: Part 4.2. Build scrapers with CDK: Create our scraper</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eb5895d9a85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-4-1-8eb5895d9a85">Build a Web-Scraped Time-Series Application With AWS CDK in TypeScript — Part 4.1</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a web-scraped time-series application with AWS CDK in TypeScript — Part 3]]></title>
            <link>https://michaelchan-13570.medium.com/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-3-9992b072f504?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9992b072f504</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 03:09:13 GMT</pubDate>
            <atom:updated>2020-11-30T12:39:30.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a web-scraped time-series application with AWS CDK in TypeScript — Part 3</h3><h4>The setup of CDK project and structure</h4><p><a href="https://medium.com/p/adbbbcf01b68">Previous: Part 2. The key and index design of DynamoDB</a></p><h3>Create The Project</h3><p>Before creating the project, please go through the <a href="https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html">prerequisite steps</a>.<br>If everything is ready, let’s run the following command in the terminal to create our project:</p><pre>mkdir world-indices-monitor-backend<br>cd world-indices-monitor-backend<br>cdk init app --language typescript</pre><p>Here I used world-indices-monitor-backend as my project name, you can use your own but do remember your difference when following this tutorial.</p><p>Project created! You should have the project like this (my cdk CLI version is 1.68.0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBCmeWgjHQmdPfqT3d0dmQ.png" /><figcaption>The freshly created project</figcaption></figure><h3>Install Dependencies</h3><p>Let’s install some basic dependencies we will need in the project:</p><pre>npm install --save @aws-cdk/aws-apigateway @aws-cdk/aws-dynamodb @aws-cdk/aws-events @aws-cdk/aws-events-targets @aws-cdk/aws-iam @aws-cdk/aws-lambda aws-sdk axios dotenv lodash simply-utils puppeteer@5.3.x puppeteer-core@5.3.x chrome-aws-lambda@5.3.x</pre><pre>npm install --save-dev @types/aws-lambda @types/lodash webpack webpack-cli webpack-bundle-analyzer @types/puppeteer file-loader@6.x</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*YdZ_hCrq84emorzUoR8QsQ.png" /><figcaption>package.json with installed dependencies</figcaption></figure><p>Let’s also talk briefly about usage of some of the uncommon dependencies:</p><ol><li>dotenv: Environment variable (secrets) storing outside of source code</li><li>simply-utils: A declarative utility library used in this project.</li><li>puppeteer , puppeteer-core A web scraping library with headless browser instance. In our project we will not directly use its source code, as simply-utils provides an abstraction for that. But we will still use its type when writing our codes. Note that puppeteer and puppeteer-core <strong>should have the same version number</strong>.</li><li>chrome-aws-lambda : A library that enables AWS lambda to use puppeteer with a chromnium instance.</li><li>file-loader : A dependency that is required by chrome-aws-lambda on build time.</li></ol><h3>Ignore node_modules for Type-checking</h3><p>If you now try to run npm run watch , you will probably got some errors from some libraries from the node_modules folder. To fix this, add &quot;skipLibCheck&quot;: true under &quot;compilerOptions&quot; of tsconfig.json to skip libraries type check.</p><h3>Configure Browser Environment for TypeScript</h3><p>Although our project is mainly on a Node environment. Since some of our codes for web-scraping later are actually on a browser/DOM environment, we have to add &quot;dom&quot; and &quot;dom.iterable&quot; to the compilerOptions.lib in tsconfig.json like the following:</p><pre>&quot;compilerOptions&quot;: {<br>  &quot;lib&quot;: [&quot;es2018&quot;, &quot;dom&quot;, &quot;dom.iterable&quot;]<br>}</pre><p>Otherwise, you might be getting some errors later on type-checking like HTMLTableRowElemen is undefined .</p><h3>Configure tsconfig.json for Node 12</h3><p>You can also configre tsconfig.json to support Node version 12 by following this <a href="https://www.npmjs.com/package/@tsconfig/node12">https://www.npmjs.com/package/@tsconfig/node12</a>.</p><h3>Add Some Scripts</h3><p>Let’s add some useful scripts:</p><pre>&quot;scripts&quot;: {<strong><br></strong>    &quot;watch&quot;<strong>:</strong> &quot;tsc --watch --noemit&quot;<strong>,<br></strong>    &quot;clearbuildcache&quot;<strong>:</strong> &quot;rm -rf ./build &amp;&amp; rm -rf ./bundles&quot;<strong>,</strong></pre><h3>The Project Structure</h3><p>I will structure the project as follows:</p><pre>/bin &lt;-- Created by CDK<br>/bundles &lt;-- bundled from build folder by webpack<br>   /cron<br>      /handlers<br>/build &lt;-- built by TypeScript<br>/src<br>   /helpers<br>   /lib<br>   /models<br>   /services<br>      /api<br>      /cron<strong><br></strong>         /handlers<br>            scrape.ts<br>            ...<br><strong>      cron.ts<br></strong>      index.ts    <br>   world-indices-monitor-backend-stack.ts</pre><ol><li><strong>src/helpers</strong>: for putting common helper functions</li><li><strong>src/lib</strong>: for putting common codes that can be grouped into some namespaces</li><li><strong>src/models</strong>: for putting app data model related codes</li><li><strong>src/services</strong>: for putting difference services, e.g. api, cron, logging etc. In this application we will have api service and cron service.</li><li><strong>build: </strong>the output directory of TypeScript build, with the exactly same folder structure as <strong>src</strong>. It is an intermediate folder which we won’t use it directly but it acts as the bundler input.</li><li><strong>bundles: </strong>containing<strong> </strong>the JavaScript files, which only includes <strong>/handlers </strong>code, bundled by webpack.</li></ol><p>Since CDK created a lib folder for us to put our source code, let’s change it to src instead. All you have to do is to change the folder name and also any import statement using the world-indices-monitor-backend-stack.ts file.</p><p>In this application our approach is putting source code and <strong>“CDK construct code” </strong>(code used to be compiled as an AWS Cloudformation template yaml file)<strong> </strong>close together, but keep in mind which is going to run and which is just for building the stack. Say in the /cron directory only the <strong>cron.ts </strong>will contain such “construct code”.</p><h3>Configure absolute import</h3><p>Add &quot;baseUrl&quot;: &quot;./&quot; under &quot;compilerOptions&quot; of tsconfig.json to allow us to import like import something from &#39;src/models/something&#39; . The reason to keep src in the import path is that we will need it later for our webpack configuration.</p><h3>Configure Jest for absolute import</h3><p>In this project we will not cover any unit-test implementation like using Jest. However, if you ever want to do so. You might need to add the <a href="https://til.hashrocket.com/posts/lmnsdtce3y-import-absolute-paths-in-typescript-jest-tests">following configuration</a> to make the absolute path works in test:</p><pre>// jest.config.js<br>module.exports = {<br>  moduleNameMapper<strong>:</strong> {<br>    &#39;src/(.*)&#39;<strong>:</strong> &#39;&lt;rootDir&gt;/src/$1&#39;<strong>,<br>  </strong>}<strong>,<br></strong>}</pre><h3>Create Services’ Constructs</h3><p>Under /src/services/cron , <strong>create</strong> cron.ts and index.ts like the following:</p><pre><strong>// cron.ts<br></strong>import * as cdk from &#39;@aws-cdk/core&#39;</pre><pre>function construct (scope: cdk.Construct): void {<br>  // CDK Construct of cron service goes here<br>}<br>export default { construct }</pre><pre><strong>// index.ts<br></strong>export { default } from &#39;./cron&#39;</pre><p><strong>Do the same</strong> for src/services/api and then <strong>call these child constructs</strong> in the main construct (PROJECT-NAME-stack.ts):</p><pre><strong>// </strong><strong>world-indices-monitor-backend-stack.ts<br></strong>import * as cdk from &#39;@aws-cdk/core&#39;<strong>;</strong></pre><pre>import api from &#39;./services/api&#39;<br>import cron from &#39;./services/cron&#39;</pre><pre>export class WorldIndicesMonitorBackendStack extends cdk.Stack {<br>  constructor(scope: cdk.Construct<strong>,</strong> id: string<strong>,</strong> props?: cdk.StackProps) {<br>    super(scope<strong>,</strong> id<strong>,</strong> props)<strong>;</strong></pre><pre>    // Initialize cron service<br>    cron.construct(this)<br>    // Initialize api service<br>    api.construct(this)<br>  }<br>}</pre><p>Let’s start setting up for scraping next!</p><p><a href="https://medium.com/p/8eb5895d9a85">Next: Part 4.1. Scraping with CDK: Setup for scraping with puppeteer, aws-chrome-Lambda, and web-pack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9992b072f504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a web-scraped time-series application with AWS CDK in TypeScript — Part 2]]></title>
            <link>https://michaelchan-13570.medium.com/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-2-adbbbcf01b68?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbbbcf01b68</guid>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-lambd]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 03:08:46 GMT</pubDate>
            <atom:updated>2020-11-05T03:08:46.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a web-scraped time-series application with AWS CDK in TypeScript — Part 2</h3><h4><strong>The key and index design of </strong>DynamoDB</h4><p><a href="https://medium.com/p/62ad98c6469f">Previous: Part 1. The application requirements, components, and architecture</a></p><h3>The Data Schema</h3><p>Although it’s not a must to pre-define a schema in NoSQL databases, it might not be the case in DynamoDB. Since DynamoDB its optimized for sorting and accessing data by <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html"><strong>key design</strong></a><strong> </strong>and<strong> </strong><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html"><strong>index design</strong></a>, it is easier for us to first have a basic schema of the important fields, and then we can <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql.html"><strong>analyze the access pattern</strong></a> before we go to table key/index design.</p><p>Based on the table displayed on <a href="https://finance.yahoo.com/world-indices/">Yahoo Finance</a> (the website we are going to scrape), our basic data schema can be look like this:</p><pre>interface IndexPriceRecord {<br>   symbol: string; // Basically an ID<br>   name: string;<br>   lastPrice: number;<br>   change: number;<br>   changeRate: number; // in %<br>   time: string; // Let&#39;s use ISOTimestamp<br>}</pre><h3>Why is key design needed?</h3><p>In DynamoDB, there are <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html"><strong>partition keys</strong></a><strong> </strong>and<strong> </strong><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-sort-keys.html"><strong>sort keys</strong></a>. Each of them at the end forms a <a href="https://www.dynamodbguide.com/key-concepts#primary-key">composite primary key</a><strong>. </strong>A partition key identifies the partition to store the item, while a sort key is used to sort items in the same partition. That means if the keys are designed well you can get an optimized throughput of the database because you always know which partition to query and related queries can happen within the same partition.</p><h3>Why is index design needed?</h3><p>When you want to list your data in a way different from how the table are sorted, you might at first sense what to <strong>scan </strong>the table with some filters. However, since a <strong>scan operation, which is </strong><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html"><strong>suggested to be avoided</strong></a><strong>, is lower and consuming more throughputs than a query operation</strong>, indexes provide a more optimized way to support different query patterns in you applications.</p><p>There are two types of indexes, <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html">Global Secondary Index (GSI)</a> and <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html">Local Secondary Index (LSI)</a>. Both at the end serve for a purpose — predefining structures different from the table which serves for some query patterns that cannot be query directly by the primary key, and to avoid scanning and filtering at runtime.</p><h3>Access Patterns</h3><p>In NoSQL database design, we are not designing our normalized data model, but instead we are going to understand our business problem for user access by <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql.html"><strong>analyzing the access patterns</strong></a>.</p><p>In our case, there might be:</p><ol><li><em>See price trend of a stock index in a certain period</em></li><li><em>Look up a list of stock indices by latest price and change rate</em></li><li><em>Look up a list of stock indices by prices and change rate in a certain period (e.g. day, week, month, quarter etc.)</em></li><li><em>Find latest price and change rate of stock indices by name or symbol</em></li><li><em>Find prices and change rate in a certain period of stock indices by name or symbol</em></li></ol><h3>Key and Indexes design</h3><p>Okay, we have got our access patterns ready. Let’s start with the key design of the <strong>base table</strong>.</p><h4><strong>Base Table</strong></h4><p>As we are going to store timeseries data, so we are going to use the strategy to create separate tables by period, <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-time-series.html">suggested by AWS</a>. As mentioned in the previous article, we are going to create a table for every month. Then our strategy and naming will be like:</p><p><em>Table creation strategy</em><strong><em>:</em></strong> <strong>Create a table each month</strong><br><em>Table naming</em>: WorldIndicesMonitor.IndicesRecords_{year}-{month}</p><p>The “WorldIndicesMonitor.” prefix is the project namespace prefix, as it might be a better practice in case you have multiple projects in a single AWS account.</p><p>It’s straightforward for the <strong>symbol being the partition key </strong>because it’s an unique identifier and it can group records of a single index into a partition. For the <strong>sort key</strong>, we will use the <strong>time</strong> field. See the following sample table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e05b9fa7d22f2a10c185d9cf8afda79/href">https://medium.com/media/1e05b9fa7d22f2a10c185d9cf8afda79/href</a></iframe><p>With the base table, we can use a query operation easily for access pattern 1. Access pattern 4 and 5 should need a <strong>scan</strong> operation in order to do advanced matching. So at this point, we can handle access pattern 1, 4, 5 with the base table. How about 2 and 3? Since our base table is partitioned by symbol, each query operation should return records of a single stock index. In order to support querying list of stock indices like access pattern 2 and 3, we are going to create an index.</p><h4><strong>GSI: Indices by Period</strong></h4><p>We will also create a Global Secondary Index (GSI) called IndicesByPeriod for query without requiring or knowing the exact symbol (Partition key of the base table). We will have a GSIHash field which is a constant value PERIOD on every item, and that field will be the partition key of the GSI. So that we can query later with just PERIOD as the partition key.</p><p><em>GSI name: </em>IndicesByPeriod</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32cc0038b776149adc49be144de0941c/href">https://medium.com/media/32cc0038b776149adc49be144de0941c/href</a></iframe><p>Alright, pretty much designing stuff now. Let’s get our hands dirty.</p><p><a href="https://medium.com/p/9992b072f504">Next: Part 3. The setup of CDK project and structure</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbbbcf01b68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a web-scraped time-series application with AWS CDK in TypeScript — Part 1]]></title>
            <link>https://michaelchan-13570.medium.com/build-a-web-scraped-time-series-application-with-aws-cdk-in-typescript-part-1-62ad98c6469f?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ad98c6469f</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[time-series-data]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 03:07:05 GMT</pubDate>
            <atom:updated>2020-11-05T03:07:05.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a web-scraped time-series application with AWS CDK in TypeScript — Part 1</h3><h4>The application requirements, components, and architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*GqnIvlmGAistvKIe.png" /><figcaption>from CDK <a href="https://docs.aws.amazon.com/cdk/latest/guide/home.html">documentation page</a></figcaption></figure><h3>The Background</h3><p>If you have been familiar with the AWS stack, you would have known about frameworks, like <a href="https://www.serverless.com/">Serverless</a>, to build AWS <a href="https://aws.amazon.com/cloudformation/"><strong>CloudFormation</strong></a><strong> </strong>stacks. With those frameworks, you have to follow their documentation to build some configuration files in like YAML format.</p><p>Recently, however, AWS has release a new development toolkit, namely <a href="https://aws.amazon.com/cdk/"><strong>Cloud Development Kit</strong></a> (a.k.a. CDK), which enables developers to <strong>configure</strong> a CloudFormation <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html#w2ab1b5c15b9"><strong>stack</strong></a><strong> </strong>without using a YAML configuration file<strong>, </strong>but <strong>with your own </strong><a href="https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html"><strong>programming languages</strong></a><strong>. </strong>At the time it supports TypeScript, JavaScript, Python, Java and C#, while <a href="https://docs.aws.amazon.com/cdk/latest/guide/multiple_languages.html">TypeScript was the first language supported</a>. That means we can <strong>configure</strong> a CloudFormation stack with more <strong>dynamic</strong> logics with <strong>scalable, reusable, traceable and testable </strong>code.</p><h3>Key Takeaway Targets</h3><p>This series tries to cover the following targets:</p><ol><li>How to build <a href="https://en.wikipedia.org/wiki/Cron"><strong>CRON</strong></a> tasks in a CDK project in TypeScript</li><li>How to build <strong>APIs</strong> in a CDK project in TypeScript</li><li>How to setup <a href="https://webpack.js.org/"><strong>webpack</strong></a><strong> </strong>to <strong>bundle lambda handlers code</strong></li><li>How to design tables and I/O flow of <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html"><strong>DynamoDB</strong></a> for <strong>time-series data</strong></li><li>How to <strong>scrape data</strong> from the web with TypeScript / JavaScript (Yes, not Python for now haha)</li></ol><h3>What We Build</h3><p>We will build <strong>a monitor application of major world stock market indices</strong>, which provides APIs to read data scraped from web and stored in database, in a single CDK project repository. The application<strong> involves the following components</strong>:</p><ol><li><strong>Database</strong>: with tables designed for time-series data</li><li><strong>CRON</strong>: tasks to scrape data periodically, to create/update tables</li><li><strong>API</strong>: with endpoints to retrieve data</li></ol><h4>The <strong>tech-stack</strong> we will use includes:</h4><ol><li>AWS <strong>DynamoDB</strong></li><li>AWS <strong>Lambda</strong>: for API requests handling and scraping data</li><li>AWS <strong>Cloudwatch Event</strong></li><li>AWS <strong>API Gateway</strong></li><li>AWS <strong>IAM</strong> Roles</li><li>AWS <strong>CloudFormation</strong></li><li><strong>Webpack</strong>: a npm library for bundling lambda TypeScript/JavaScript sources</li><li><strong>Puppeteer</strong>: a npm library for web scraping with headless browser instance</li></ol><h3>Application Requirements</h3><p>This project focuses on the backend only, and it should cover the following requirements:</p><ol><li>The application should <strong>scrape</strong> the prices data of world indices <strong>every hour </strong>from<strong> </strong><a href="https://finance.yahoo.com/world-indices/">https://finance.yahoo.com/world-indices/</a>. Usually the data should be updated more frequently, but since this is just for demonstration purpose, let’s just make it <strong>hourly</strong> first.</li><li>The application should provides <strong>API</strong> for accessing the scraped, and aggregated data.</li><li>It’s supposed that <strong>data of the current month will gain the highest retrieval rate</strong>, while the other will be less depending on the duration between the current month.</li></ol><h3>Application Components</h3><p>The application can be splitted into following components:</p><h4><strong>A. CRON jobs for table manipulation</strong></h4><p>This component is for <strong>creating/updating tables</strong> according to best practices for <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-time-series.html">handling time-series data in DynamoDB</a>. This article will not focus on the concept of design pattern of time-series tables. To further study that, read <a href="https://medium.com/mfine-technology/how-we-store-time-series-data-with-dynamodb-and-node-js-29cd917cadfa">this article</a>.</p><p>Let’s assume the pattern of name of our tables will be like WorldIndices_{year}-{month}. This component can be further separated into:</p><ol><li>CRON job for<strong> table creation<br></strong>At the <strong>end</strong> of every period (month), create a new table for the next period. E.g. tableWorldIndices_2020-11 will be created at the end of October 2020 .</li><li>CRON job for <strong>table throughputs update<br></strong>At the <strong>start</strong> of every period (month), decrease the throughputs of table of previous period. E.g. The provisioned throughputs of table WorldIndices_2020-11 will be decreased to a certain level at the start of December 2020.</li></ol><h4><strong>B. CRON job for scraping data</strong></h4><p>This<strong> </strong>component is for scraping data from the website <strong>hourly </strong>which shows updated prices data of stock market indices, and storing them into our database.</p><h4><strong>C. API</strong></h4><p>This component is just simply providing an interface for any other program or frontend code to retrieve the data.</p><h3>Application Architecture</h3><p>The basic application architecture is as simple as the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEkJvk3xtMeaAZeuFxwyzA.png" /><figcaption>The basic application archectiture</figcaption></figure><p>Basically there are three Lambda handlers for CRON jobs, which are all trigger by events with different time-based rules. There are nothing special here but just let you have a visual of the application components and flow.</p><p>Okay, let’s start designing the database.</p><p><a href="https://medium.com/p/adbbbcf01b68/">Next: Part 2. The key and index design of DynamoDB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ad98c6469f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync I18next JSON files with just ONE Comand]]></title>
            <link>https://michaelchan-13570.medium.com/sync-i18next-json-files-with-just-one-comand-9df330fe0760?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df330fe0760</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-i18n]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[i18next]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 10:24:46 GMT</pubDate>
            <atom:updated>2020-02-26T10:49:45.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Given my recent experience of developing a large scale React project, I’ve found that there are rarely exmaples of how to implement continuous localization easily for using the i18next file structure. If you are using the same/similar <strong>i18next file structure</strong> like my project as follows, you’re lucky…</p><pre>/src<br>   /locales<br>      /data &lt;-- (Putting into this folder is optional, just my case)<br>         /en<br>            dashboard.json<br>            product.json<br>         /zh-HK<br>            dashboard.json<br>            product.json</pre><p>Let’s say the /en/dashboard.json is like this:</p><pre>{ <br>  &quot;title&quot;: &quot;Dashboard&quot;, <br>  &quot;description&quot;: &quot;Your dashboard of products.&quot;<br>}</pre><p>And the /zh-HK/dashboard.json is like this:</p><pre>{ <br>  &quot;title&quot;: &quot;儀表版&quot;, <br>  &quot;description&quot;: &quot;你的產品儀表版&quot;<br>}</pre><p>Now say I want to add an &quot;remark&quot; text in the dashboard.json . In normal way you have to copy-and-paste that key to eachdasboard.json of every locale (in this case, /en and zh-HK ). It is still OK when you have only two language folders. But what if you have more then ten languages or you just missed one file and you didn’t know?</p><p>To streamline that process, I created a script to synchronize all JSON files of every locale, which would most likely just require you to type one command node syncI18nJSONs.js, after you have added some changes to one language. What it actually does is simply copy the JSON files of the base language, in my case en , to the JSON files of other languages <strong>without overwriting existing translation text </strong>(if there is any bug please tell me:).</p><h3>Source</h3><p><strong>You can download the script here: </strong><a href="https://gist.github.com/michchan/d3bb3a3f6c7a66c8971305713503ef5d"><strong>https://gist.github.com/michchan/d3bb3a3f6c7a66c8971305713503ef5d</strong></a></p><p><strong>NOTE that </strong>you might need to change the following:</p><ul><li><strong>Change folder path:</strong> You have to change the folder path according to your project on the line: const LOCALES_PATH = &#39;src/locales/data&#39; . The default value &#39;src/locales/data’ is just my case. You can also put it say outside of the src folder like &#39;public/locales&#39;. The reason I don’t make it an argument is because you nearly won’t need to modify it once defined.</li><li><strong>Change base language: </strong>You can also change the locale name of the base language on the line: const BASED_LNG = &#39;en&#39; .</li></ul><h3>Usage Example</h3><ol><li>Say my /en/dashboard.json now become like this:</li></ol><pre>{ <br>  &quot;title&quot;: &quot;Dashboard&quot;, <br>  &quot;description&quot;: &quot;Your dashboard of products.&quot;,<br>  &quot;remark&quot;: &quot;Note that these data are updated hourly.&quot;<br>}</pre><p>2. Now I want the /zh-HK/dashboard.json to have the same structure. I just need to run node syncI18nJSON.js .</p><p>3. DONE! Now the /zh-HK/dashboard.json should become like:</p><pre>{ <br>  &quot;title&quot;: &quot;儀表版&quot;, <br>  &quot;description&quot;: &quot;你的產品儀表版&quot;,<br>  &quot;remark&quot;: &quot;&quot;<br>}</pre><p>There are also some advanced usage but since they are not quite common so I won’t cover them here. I would be pleased if anyone feels this is useful. <strong>Feel free to raise if there is any question/issue.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df330fe0760" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using React-Router v4 Prompt with custom modal component]]></title>
            <link>https://michaelchan-13570.medium.com/using-react-router-v4-prompt-with-custom-modal-component-ca839f5faf39?source=rss-d82560d346a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca839f5faf39</guid>
            <category><![CDATA[react-router-4]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Chan]]></dc:creator>
            <pubDate>Sun, 23 Dec 2018 13:25:26 GMT</pubDate>
            <atom:updated>2022-07-15T03:13:41.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using React-Router v4/v5 Prompt with custom modal component</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBHQwb2Mpt63EVeBsoTUtA.png" /><figcaption>React-Router v4 Prompt on Safari</figcaption></figure><h3>The Problem</h3><p>With React-Router <strong>v4</strong>, we can easily insert route blocking logic into any scene using <strong>Prompt, </strong>passing<strong> </strong>only two props: <em>when</em> and <em>message. </em>However, there seem no explicit official docs telling how to implement custom modal instead of the default modal provided by Prompt. This might be okay if your app doesn’t require custom modal UI and 100% localization. Otherwise, the Prompt default modal might not match your requirement since it does not provide props for custom styles and button label text (say I want to implement localized label text .i.e. yes/no). There are other solutions provided in the community using the <strong>getUserConfirmation </strong>prop of BrowserRouter, which might be hardly implemented inside each scene components independently.</p><h3><strong>A Simple Solution</strong></h3><p>In the official docs of ReactRouter/Prompt, the message prop is a function which:</p><blockquote>Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.</blockquote><p>That means when the function returns a string, Prompt will show up, while navigation will be allowed if it returns true.</p><p>That has actually not ended. When you tries to return false<em> </em>from the function, what will happen?</p><p>Nothing will happen. More accurately, <strong>the navigation will be blocked while the default Prompt modal does not show up too.</strong></p><p>Gotcha! That means we can hook some logic to show our custom modal before returning false<strong><em> </em></strong>too. We can also check whether we should block the navigation here according to next location and a state telling whether the user has confirmed navigation.</p><p>Then our function passed to the message prop can be like this:</p><pre>handleBlockedRoute = (nextLocation) =&gt; {<br>   const {confirmedNavigation} = this.state<br>   const {shouldBlockNavigation} = this.props</pre><pre>   if (<strong>!</strong>confirmedNavigation <strong>&amp;&amp; </strong>shouldBlockNavigation(nextLocation)){<br>       this.showModal(nextLocation)<br>       return false<br>   }<br>   <br>   return true<br>}</pre><p>The following is the <strong>full implementation</strong>:</p><p><strong>JavaScript and Class version:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4994fb9cdf8f017d48b1a550657b3f89/href">https://medium.com/media/4994fb9cdf8f017d48b1a550657b3f89/href</a></iframe><p><strong>Usage:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e933cd81766efb3ecb0bb4cd0de5c669/href">https://medium.com/media/e933cd81766efb3ecb0bb4cd0de5c669/href</a></iframe><p><strong>TypeScript and React 16+ version (Thanks to </strong><a href="https://medium.com/u/af506ded45e3?source=post_page-----ca839f5faf39--------------------------------"><strong>Roger</strong></a><strong>):</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e12a25b032c840e3b7901c6d395542c/href">https://medium.com/media/5e12a25b032c840e3b7901c6d395542c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca839f5faf39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>