<?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 Hamza Makhkhas on Medium]]></title>
        <description><![CDATA[Stories by Hamza Makhkhas on Medium]]></description>
        <link>https://medium.com/@hamzamakh?source=rss-4122279b8d88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KdyujDDWuabhkd2wyHmgGA.jpeg</url>
            <title>Stories by Hamza Makhkhas on Medium</title>
            <link>https://medium.com/@hamzamakh?source=rss-4122279b8d88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:16:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamzamakh/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[Building Micro Frontends in Angular with @angular-architects/native-federation]]></title>
            <link>https://medium.com/@hamzamakh/building-micro-frontends-in-angular-with-angular-architects-native-federation-bf6cc28a4a51?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf6cc28a4a51</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[modularity]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 14:43:04 GMT</pubDate>
            <atom:updated>2024-11-03T14:49:22.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*wPwqi_tOzUQUKZtvQvddsg.png" /><figcaption>Angular with Native Federation</figcaption></figure><h3>Introduction</h3><p>Micro frontends allow teams to develop and deploy parts of a large application independently, enhancing scalability and maintainability. Using the <strong>@angular-architects/native-federation</strong> library, we can simplify the setup of micro frontends in Angular with Webpack Module Federation. In this tutorial, we’ll create a shell (host) application and a todo (remote) application, which the shell will dynamically load.</p><h3>Prerequisites</h3><ul><li>Node.js and npm installed</li><li>Angular CLI installed (npm install -g @angular/cli)</li></ul><h3>Step 1: Set Up Angular Workspace</h3><p>First, create a new Angular workspace without an initial application.</p><pre>ng new my-workspace --create-application=false</pre><p>This sets up a blank workspace where we can add multiple applications.</p><h3>Step 2: Generate Applications (Shell and Todo)</h3><p>Next, generate two Angular applications within this workspace: the <strong>Shell</strong> (host) application and the <strong>Todo</strong> (remote) application.</p><pre>cd my-workspace<br>ng generate application shell --prefix app-shell<br>ng generate application todo --prefix app-todo</pre><p>The shell app will act as the host, while the todo app will be the micro frontend (remote module).</p><h3>Step 3: Install @angular-architects/native-federation</h3><p>Install the <strong>@angular-architects/native-federation</strong> package, which simplifies the setup of module federation for Angular applications.</p><pre>npm install -D @angular-architects/native-federation</pre><h3>Step 4: Configure Shell Application as the Host</h3><p>Set up the <strong>Shell</strong> application to act as a host that will load the <strong>Todo</strong> application at runtime.</p><p>Run the following command to configure the shell project:</p><pre>ng g @angular-architects/native-federation:init --project shell --port 4200 --type dynamic-host</pre><ul><li>--project shell specifies that we’re setting up the shell application.</li><li>--port 4200 sets the port for this application.</li><li>--type dynamic-host configures the application to dynamically load remotes.</li></ul><p>This command generates and updates Webpack configurations to make the shell a host application.</p><h3>Step 5: Configure Todo Application as the Remote</h3><p>Next, configure the <strong>Todo</strong> application as a remote module that the shell application will load.</p><pre>ng g @angular-architects/native-federation:init --project todo --port 4201 --type remote</pre><ul><li>--project todo specifies the todo application.</li><li>--port 4201 sets the port for this application.</li><li>--type remote configures the application as a remote module.</li></ul><p>This command creates a remoteEntry.js file that allows the shell to load the <strong>Todo</strong> module dynamically.</p><h3>Step 6: Create and Expose a Component in the Todo Application</h3><p>In the <strong>Todo</strong> application, create a new component that we’ll expose as a remote module.</p><pre>ng generate component pages/todo-list --project todo</pre><p>Now, update the <strong>Todo</strong> app’s angular.json configuration to expose the <strong>TodoListComponent</strong>.</p><p>In the projects/todo/webpack.config.js file, find the exposes section and add the path to your component:</p><pre>module.exports = {<br>  // existing configuration...<br>  exposes: {<br>    &#39;./Component&#39;: &#39;./src/app/pages/todo-list/todo-list.component.ts&#39;,<br>  },<br>  // other configuration...<br>};</pre><p>This configuration exposes the TodoListComponent so it can be loaded by the shell application.</p><h3>Step 7: Update Routing in the Shell Application</h3><p>In the <strong>Shell</strong> application, configure routes to load the <strong>Todo</strong> remote module. First, generate a new home component:</p><pre>ng generate component pages/home --project shell</pre><p>Next, configure the <strong>Shell</strong> application’s routing module to load the remote module on demand.</p><p>In shell/src/app/app.routes.ts, configure the routes as follows:typescr</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { loadRemoteModule } from &#39;@angular-architects/native-federation&#39;;<br>import { HomeComponent } from &#39;./pages/home/home.component&#39;;<br><br>export const routes: Routes = [<br>  { path: &#39;&#39;, component: HomeComponent },<br>  {<br>    path: &#39;todo&#39;,<br>    loadComponent: () =&gt;<br>      loadRemoteModule({<br>        remoteName: &#39;todo&#39;,<br>        exposedModule: &#39;./Component&#39;,<br>      }).then(m =&gt; m.TodoListComponent),<br>  },<br>  { path: &#39;**&#39;, component: HomeComponent },<br>];</pre><p>Here’s a breakdown of this configuration:</p><ul><li>HomeComponent serves as the default route.</li><li>The /todo route dynamically loads TodoListComponent from the remote <strong>Todo</strong> application.</li><li>A wildcard route (**) redirects any unknown paths to the home page.</li></ul><h3>Step 8: Update Shell Application Template</h3><p>Update the <strong>Shell</strong> application’s template to add navigation between the <strong>Home</strong> and <strong>Todo</strong> components.</p><p>In shell/src/app/app.component.html, add the following:</p><pre>&lt;ul&gt;<br>  &lt;li&gt;&lt;a routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>  &lt;li&gt;&lt;a routerLink=&quot;/todo&quot;&gt;Todo&lt;/a&gt;&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><h3>Step 9: Run Both Applications</h3><p>Now, it’s time to run both applications and test if the <strong>Shell</strong> application can dynamically load the <strong>Todo</strong> component.</p><p>In separate terminal windows, run:</p><pre>ng serve shell<br>ng serve todo</pre><p>Navigate to http://localhost:4200 in your browser. You should see the <strong>Home</strong> component, and by clicking on the <strong>Todo</strong> link, the <strong>TodoListComponent</strong> should load dynamically from the remote <strong>Todo</strong> application.</p><h3>Step 10: Configure Production Deployment (Optional)</h3><p>In a production environment, ensure that the URLs for remote modules are updated to point to the production server. For example, in the <strong>Shell</strong> app’s webpack.config.js, update the remotes configuration as follows:</p><pre>remotes: {<br>  todo: &quot;todo@https://your-prod-url.com/remoteEntry.js&quot;,<br>}</pre><p>This ensures that the shell loads the remote modules from the correct URLs when deployed to production.</p><h3>Conclusion</h3><p>With <strong>@angular-architects/native-federation</strong>, setting up micro frontends in Angular is streamlined and efficient. This approach allows you to independently develop, test, and deploy different parts of your application, which is particularly beneficial for large-scale projects.</p><p>This setup not only enhances modularity and scalability but also enables different teams to work on separate micro frontends with minimal dependencies on each other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf6cc28a4a51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Micro Frontends in Angular Using Module Federation]]></title>
            <link>https://medium.com/@hamzamakh/building-micro-frontends-in-angular-using-module-federation-f4d64358a701?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d64358a701</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[modularity]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 14:15:33 GMT</pubDate>
            <atom:updated>2024-11-03T14:48:03.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtPQ6XfnH7ZryTfowDu6Jg.png" /></figure><p>Micro frontends have gained popularity for their ability to break down monolithic frontend applications into smaller, manageable, and independently deployable units. In this tutorial, we’ll explore <strong>what micro frontends are</strong>, <strong>why they’re beneficial</strong>, and <strong>how to implement them in Angular</strong> using <strong>Webpack Module Federation</strong>.</p><p>By the end of this guide, you’ll know how to set up, configure, and deploy Angular applications using micro frontend architecture.</p><h3>Table of Contents</h3><ol><li>What are Micro Frontends?</li><li>Why Use Micro Frontends in Angular?</li><li>Introduction to Module Federation</li><li>Setting up Your Angular Project</li><li>Creating and Configuring Micro Frontends</li><li>Sharing Modules and Dependencies</li><li>Testing and Deploying Your Micro Frontend Application</li><li>Conclusion</li></ol><h3>1. What are Micro Frontends?</h3><p>Micro frontends bring the microservices approach to the frontend. Instead of building one large monolithic frontend, you split it into smaller, independent applications, each responsible for its own features.</p><ul><li><strong>Decoupling and Independent Deployment</strong>: Each micro frontend can be developed, tested, and deployed independently.</li><li><strong>Technology Agnosticism</strong>: Different micro frontends can use different frameworks if needed, though this is less common with Angular-specific micro frontends.</li><li><strong>Scalability and Maintenance</strong>: It’s easier to maintain smaller applications and add features without affecting the entire application.</li></ul><h3>2. Why Use Micro Frontends in Angular?</h3><p>Angular applications can become large and complex over time, which can lead to challenges in scalability, maintainability, and deployment. Here’s why micro frontends with module federation are beneficial in Angular:</p><ul><li><strong>Independent Teams and Development</strong>: Teams can work on different parts of the application without affecting each other.</li><li><strong>Optimized Loading</strong>: Only load the parts of the application that are required, resulting in faster load times.</li><li><strong>Version Control</strong>: Each micro frontend can use a specific version of libraries, reducing compatibility issues.</li></ul><h3>3. Introduction to Module Federation</h3><p>Module Federation, introduced in Webpack 5, allows JavaScript applications to dynamically import code from other applications at runtime. This is ideal for micro frontends, as it enables seamless integration of multiple Angular applications.</p><h4>Key Concepts in Module Federation:</h4><ul><li><strong>Host</strong>: The main application that consumes other micro frontends.</li><li><strong>Remote</strong>: The micro frontend applications being consumed.</li><li><strong>Shared Modules</strong>: Modules that need to be shared between the host and remotes, such as Angular core libraries.</li></ul><h3>4. Setting up Your Angular Project</h3><p>Let’s start by setting up an Angular workspace that will serve as the host and another application that will serve as a remote.</p><h4>Step 1: Install Angular CLI and Create Projects</h4><pre>npm install -g @angular/cli<br>ng new microfrontend-host --routing --style=scss<br>ng new microfrontend-remote --routing --style=scss</pre><p>In this example, microfrontend-host will act as the host, and microfrontend-remote will be the micro frontend.</p><h4>Step 2: Install Webpack 5 and Module Federation</h4><p>To use module federation, make sure Webpack 5 is enabled in your Angular CLI:</p><pre>ng add @angular-architects/module-federation --project microfrontend-host<br>ng add @angular-architects/module-federation --project microfrontend-remote</pre><p>This command automatically configures the projects for module federation and creates configuration files.</p><h3>5. Creating and Configuring Micro Frontends</h3><p>In this section, we’ll configure the host and remote applications to use module federation.</p><h4>Step 1: Configure the Host</h4><p>In webpack.config.js of the microfrontend-host, configure it to load remote applications dynamically:</p><pre>const ModuleFederationPlugin = require(&quot;webpack/lib/container/ModuleFederationPlugin&quot;);<br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;microfrontendHost&quot;,<br>      remotes: {<br>        microfrontendRemote: &quot;microfrontendRemote@http://localhost:4201/remoteEntry.js&quot;,<br>      },<br>      shared: {<br>        &quot;@angular/core&quot;: { singleton: true },<br>        &quot;@angular/common&quot;: { singleton: true },<br>        &quot;@angular/router&quot;: { singleton: true },<br>      },<br>    }),<br>  ],<br>};</pre><h4>Step 2: Configure the Remote</h4><p>In webpack.config.js of the microfrontend-remote, configure it to expose specific modules:</p><pre>const ModuleFederationPlugin = require(&quot;webpack/lib/container/ModuleFederationPlugin&quot;);<br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;microfrontendRemote&quot;,<br>      filename: &quot;remoteEntry.js&quot;,<br>      exposes: {<br>        &#39;./Module&#39;: &#39;./src/app/your-feature/your-feature.module.ts&#39;,<br>      },<br>      shared: {<br>        &quot;@angular/core&quot;: { singleton: true },<br>        &quot;@angular/common&quot;: { singleton: true },<br>        &quot;@angular/router&quot;: { singleton: true },<br>      },<br>    }),<br>  ],<br>};</pre><p>This configuration makes the feature module in microfrontend-remote available for import by the host application.</p><h3>6. Sharing Modules and Dependencies</h3><p>Using module federation, we want to avoid loading multiple versions of the same library. In the configuration above, we specified @angular/core, @angular/common, and @angular/router as shared dependencies to ensure that only one version is loaded.</p><h3>7. Testing and Deploying Your Micro Frontend Application</h3><h4>Step 1: Start Both Applications</h4><p>Run both applications in development mode to verify that the host can successfully load the remote module.</p><pre>ng serve microfrontend-host --port 4200<br>ng serve microfrontend-remote --port 4201</pre><p>Now, navigate to http://localhost:4200 (host application) and test if it correctly loads components from http://localhost:4201 (remote application).</p><h4>Step 2: Configure Production Deployment</h4><p>When deploying to production, ensure that remoteEntry.js URLs are updated to point to the production servers. For example:</p><pre>remotes: {<br>  microfrontendRemote: &quot;microfrontendRemote@https://your-prod-url.com/remoteEntry.js&quot;,<br>}</pre><h3>8. Conclusion</h3><p>Micro frontends with module federation in Angular provide a powerful architecture for building large-scale applications. This approach enables independent development, faster loading times, and better scalability.</p><p>While the traditional Webpack Module Federation setup provides a high degree of control over the configuration and dependencies in a micro frontend architecture, it can involve complex setup and maintenance, especially for large Angular applications.</p><p><strong>@angular-architects/native-federation</strong> simplifies this process, specifically tailored for Angular developers. By using Angular-centric helper functions like loadRemoteModule and automating much of the setup, it makes implementing micro frontends faster and more straightforward. This streamlined approach is especially beneficial for teams looking to get started with micro frontends in Angular without diving into extensive Webpack configurations.</p><p>If you’re interested in a simpler, Angular-focused approach to micro frontends, check out my <a href="https://medium.com/@hamzamakh/building-micro-frontends-in-angular-with-angular-architects-native-federation-bf6cc28a4a51">guide on building micro frontends with @angular-architects/native-federation</a> to learn how to set up and deploy a modular Angular architecture with minimal configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d64358a701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Optimize Node.js App with API Caching Using Redis]]></title>
            <link>https://medium.com/@hamzamakh/how-to-optimize-node-js-app-with-api-caching-using-redis-4bda7961009?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bda7961009</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 18:55:36 GMT</pubDate>
            <atom:updated>2023-06-21T21:16:24.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RrBbLM_rMXEBrvi4JxViYw.jpeg" /></figure><h4>Introduction</h4><p>Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides <a href="https://redis.io/docs/data-types/">data structures</a> such as <a href="https://redis.io/docs/data-types/strings/">strings</a>, <a href="https://redis.io/docs/data-types/hashes/">hashes</a>, <a href="https://redis.io/docs/data-types/lists/">lists</a>, <a href="https://redis.io/docs/data-types/sets/">sets</a>, <a href="https://redis.io/docs/data-types/sorted-sets/">sorted sets</a></p><h4>Installation</h4><p>To install Redis, Visit the official Redis website (<a href="https://redis.io/">https://redis.io/</a>) and navigate to the download page. You can download the latest stable release or choose a specific version that suits your needs.</p><p>By default, Redis will run on the default port 6379. If you wish to use a different port, you can specify it with the --port flag, like this:</p><pre>redis-server --port 1234</pre><p>To start the Redis command-line interface (CLI), open a terminal or command prompt and write redis-cli</p><p>First open a terminal and write redis-cli , you should see something like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*KKeUn5OTYZ8binGQQBMJRg.png" /></figure><p>Here are some basic commands to interact with Redis once running:</p><ol><li>SET: Set the value of a key.</li></ol><pre>SET key value</pre><p>2. GET: Get the value of a key.</p><pre>GET key</pre><p>3. DEL: Delete a key and its associated value.</p><pre>DEL key</pre><p>4. EXPIRE: Set a key’s expiration time in seconds.</p><pre>EXPIRE key seconds</pre><p>5. FLUSHALL: Remove all keys from the current database.</p><pre>FLUSHALL</pre><p>You can refer to the official Redis documentation (<a href="https://redis.io/documentation">https://redis.io/documentation</a>) for a comprehensive list of commands and their usage.</p><h4>How use Redis with nodejs</h4><p>In Node.js, there are several Redis libraries available for interacting with Redis servers. Some of the popular ones include:</p><ol><li><a href="https://github.com/redis/ioredis">ioredis</a>: A robust, full-featured Redis client with high performance and support for both Node.js callbacks and Promises.</li><li><a href="https://github.com/redis/redis">redis</a>: The original Redis client for Node.js, providing a simple and straightforward interface to interact with Redis.</li><li><a href="https://github.com/redis/node-redis">node_redis</a>: A widely-used Redis client for Node.js that offers a rich feature set and supports both callbacks and Promises.</li><li><a href="https://github.com/moaxaca/async-redis">redis-async</a>: A lightweight Redis client that uses async/await syntax and provides a simplified API for Redis operations.</li></ol><p>Now let’s focus on using the <strong>ioredis</strong> library specifically for API caching with Redis.</p><p><strong>Step 1:</strong> Install ioredis To get started, you need to install the ioredis library in your Node.js project. You can do this using npm or yarn:</p><pre>npm install ioredis // using npm<br>yarn add ioredis   // using yarn</pre><p><strong>Step 2:</strong> Create a Redis client instance Once you have ioredis installed, you can create a Redis client instance in your Node.js application. Here&#39;s an example:</p><pre>const Redis = require(&#39;ioredis&#39;);<br><br>// Create a Redis client instance<br>const redis = new Redis({<br>  host: &#39;localhost&#39;, // Redis server host<br>  port: 6379, // Redis server port<br>});</pre><p>Adjust the host and port values according to your Redis server configuration.</p><p>By default, if you don’t mention the host and the port ,it connects to localhost:6379</p><p><strong>Step 3:</strong> Caching API responses with Redis To cache API responses using Redis, you can use the set and get methods provided by the ioredis library. Here&#39;s an example:</p><pre>// Cache an API response<br>async function cacheApiResponse(key, data) {<br>  // Convert the data to a JSON string<br>  const json = JSON.stringify(data);<br><br>  // Store the JSON string in Redis with an expiration of 1 hour (3600 seconds)<br>  await redis.set(key, json, &#39;EX&#39;, 3600);<br>}<br><br>// Retrieve a cached API response<br>async function getCachedApiResponse(key) {<br>  // Get the JSON string from Redis<br>  const json = await redis.get(key);<br><br>  if (json) {<br>    // Parse the JSON string back into an object<br>    return JSON.parse(json);<br>  }<br><br>  return null; // Return null if the key does not exist in the cache<br>}</pre><p>Remember to handle error scenarios, implement cache invalidation strategies, and adjust the caching logic according to your specific requirements.</p><h3>How To Use redis Cahing Api with Mongodb Or with any database :</h3><p>To organize things, you can create a new directory named utils and add a file called redis-cache.js. Then, we can write all the logic of using Redis in it. We will create only two functions for the sake of this tutorial.</p><p>getOrSetCache Function:</p><ul><li>This function is defined to generalize the process of caching data. It accepts two parameters: key and cb (callback function).</li><li>It returns a promise that resolves to either the cached data or the freshly retrieved data.</li></ul><p>clearCache Function:</p><ul><li>This function is defined to clear the entire cache stored in the Redis server.</li></ul><pre>import { Redis } from &quot;ioredis&quot;<br>// or const Redis = require(&quot;ioredis&quot;); if you using CommonJS syntax<br><br>// Create a Redis client instance<br>const redisClient = new Redis();<br><br>// Default expiration time for cached data (2 hours)<br>const DEFAULT_EXPIRATION = 7200; // en seconds<br><br>// Function to get or set cache<br>export function getOrSetCache(key, cb) {<br>    return new Promise(async (resolve, reject) =&gt; {<br>        // Try to get data from Redis using the provided key<br>        const data = await redisClient.get(key)<br>            .catch(error =&gt; {<br>                console.log(error);<br>                return reject(error);<br>            })<br><br>        // If data exists in cache, parse and return it<br>        if (data) return resolve(JSON.parse(data));<br><br>        // If data doesn&#39;t exist in cache, invoke the callback function (cb) to fetch fresh data<br>        const freshData = await cb();<br><br>        // Store the fresh data in Redis cache with the specified key and expiration time<br>        redisClient.set(key, JSON.stringify(freshData), &#39;EX&#39;, DEFAULT_EXPIRATION);<br><br>        // Resolve the promise with the fresh data<br>        resolve(freshData);<br>    })<br>}<br><br>// Function to clear the entire cache<br>export async function clearCache() {<br>    console.log(&quot;cache cleared&quot;);<br>    // Flush all keys from the Redis cache<br>    await redisClient.flushall();<br>}</pre><p>Here’s an example that demonstrates the usage , we gonna create a get route :</p><pre>import express from &quot;express&quot;;<br><br>import {getRoomsByIdUser } from &quot;../controllers/rooms.js&quot;;<br>import auth from &quot;../middleware/auth.js&quot;; // for authentification<br><br>const router = express.Router();<br>router.get(&#39;/:userId&#39;,auth, getRoomsByIdUser)<br><br>export default router</pre><p>if you unfamiliar with authentification and authorization , you can read about it in this <a href="https://medium.com/@hamzamakh/authentication-and-authorization-using-jwt-with-node-js-39a0dfb6cbc6">blog</a>.</p><p>then let’s implement the ‘ getRoomsByIdUser ‘ function :</p><pre>import { getOrSetCache } from &#39;./path/to/cache&#39;; // Replace &#39;./path/to/cache&#39; with the actual path to your cache file<br><br>export const getRoomsByIdUser = async (req, res) =&gt; {<br>  const { userId } = req.params; // or retrieve userId from <br>// or //if(!req.userId) return res.status(404).send(`Not Authentificated`);<br><br>  try {<br>      const rooms = await getOrSetCache(userId, async () =&gt; {<br>        // cb function<br>        let data = await Room.find({ professeur: userId })<br>          .sort({ _id: -1 })<br>        return data;<br>      });<br><br>      // Use the &#39;rooms&#39; data as needed<br>      res.json(rooms);<br>    catch (error) {<br>    res.status(500).send(&quot;An error occurred&quot;); <br>  }<br>};</pre><ul><li>We calls the getOrSetCache function, passing the userId as the cache key and an async callback function.</li><li>The getOrSetCache attempts to fetch the data associated with the userId from the cache. If the data is not present in the cache, it executes the provided callback function and stores the returned data from Mongodb in the cache. In this case, the callback function is defined as an async arrow function.</li></ul><p>the first request take about<strong> 1073 ms</strong> , now the data will be stored in the cache</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzPaAHl40_rXPXUgNLSgxw.png" /></figure><p>let’s verify this is well stored in redis database :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*4Be_QsYwzoVeNAM95MjHmA.png" /><figcaption>stored successfully</figcaption></figure><p>Now , the next time I request this query it will fetch it from redis not mongodb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLego5-w9PamdKpFZwKUug.png" /></figure><p>you can see it takes only <strong>141 ms</strong> .</p><p>That’s it! You now have a basic understanding of how to use the ioredis library in Node.js to optimize your app with API caching using Redis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bda7961009" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorization Using JWT With Node.js]]></title>
            <link>https://medium.com/@hamzamakh/authentication-and-authorization-using-jwt-with-node-js-39a0dfb6cbc6?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a0dfb6cbc6</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 12:48:08 GMT</pubDate>
            <atom:updated>2023-06-19T13:00:07.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*4jmXTlBEO9687iSDPy8KBg.png" /><figcaption>JWT with node.js app</figcaption></figure><p>To implement authentication and authorization using JSON Web Tokens (JWT) in Express, you can follow these steps:</p><p><strong>Step 1:</strong> Install Dependencies First, you need to install the necessary dependencies. Open your terminal and navigate to your Express project directory, then run the following command:</p><pre>npm install jsonwebtoken</pre><p><strong>Step 2:</strong> Set up JWT Middleware</p><p>Create a new file called jwtMiddleware.js and add the following code:</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br><br>function verifyToken(req, res, next) {<br>  const token = req.headers[&#39;authorization&#39;];<br><br>  if (!token) {<br>    return res.status(401).json({ message: &#39;No token provided&#39; });<br>  }<br><br>  jwt.verify(token, &#39;your_secret_key&#39;, (err, decoded) =&gt; {<br>    if (err) {<br>      return res.status(403).json({ message: &#39;Failed to authenticate token&#39; });<br>    }<br><br>    req.userId = decoded.userId;<br>    next();<br>  });<br>}<br><br>module.exports = verifyToken;</pre><p>Make sure to replace &#39;your_secret_key&#39; with your own secret key. This middleware function will verify the token and attach the decoded userId to the request object (req.userId) if the token is valid.</p><p><strong>Step 3:</strong> Create Authentication and Authorization Routes In your Express application, create routes for authentication and authorization. For example, you can have routes for registering, logging in, and accessing protected resources. Here’s an example:</p><pre>const express = require(&#39;express&#39;);<br>const jwtMiddleware = require(&#39;./jwtMiddleware&#39;);<br><br>const app = express();<br><br>// Authentication route<br>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  // Perform authentication logic<br>  // Assuming the user is authenticated successfully<br>  const userId = 123; // Get the user ID from your authentication logic<br><br>  // Create and sign the token<br>  const token = jwt.sign({ userId }, &#39;your_secret_key&#39;);<br><br>  // Send the token back to the client<br>  res.json({ token });<br>});<br><br>// Protected route<br>app.get(&#39;/protected&#39;, jwtMiddleware, (req, res) =&gt; {<br>  // Access the user ID from the request object<br>  const userId = req.userId;<br><br>  // Use the user ID to fetch protected resources<br>  // Return the resources to the client<br>  res.json({ userId, data: &#39;Protected data&#39; });<br>});<br><br>// Start the server<br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server started on port 3000&#39;);<br>});</pre><p>In the /login route, you perform the authentication logic, generate a token using jwt.sign(), and send the token back to the client.</p><p>In the /protected route, you add the jwtMiddleware as middleware. This middleware will verify the token and attach the userId to the request object. If the token is invalid or missing, the middleware will return an appropriate response.</p><p><strong>Step 4:</strong> Test the Authentication and Authorization Start your Express server (node app.js or npm start) and use a tool like Postman or curl to test the routes.</p><ol><li>Send a POST request to /login with any necessary credentials. You should receive a token in the response.</li><li>Copy the token from the response.</li><li>Send a GET request to /protected and include the token in the Authorization header as Bearer &lt;token&gt;. You should receive a response with the protected data and the user ID.</li></ol><p>That’s it! You’ve implemented authentication and authorization using JWT in Express. Remember to handle token expiration, token refresh, and securely storing the secret key in a production environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a0dfb6cbc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping in python]]></title>
            <link>https://medium.com/@hamzamakh/web-scraping-in-python-817d8096e65f?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/817d8096e65f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 11:49:01 GMT</pubDate>
            <atom:updated>2023-06-16T11:49:01.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYI60ZSxY0M8gD0_9JQrdg.png" /></figure><h4>Introduction :</h4><p>Web scraping is the process of automatically extracting data from websites. It involves retrieving the HTML content of a web page, parsing it, and extracting specific information or data points. Web scraping allows you to gather data from multiple web pages efficiently and programmatically, without the need for manual copying and pasting.</p><blockquote><strong>Web scraping has various use cases and applications:</strong></blockquote><ol><li><strong>Data Collection: </strong>Web scraping enables you to collect large amounts of data from different websites, such as product information, prices, reviews, contact details, or news articles.</li><li><strong>Market Research:</strong> By scraping data from e-commerce websites or social media platforms, you can gain insights into market trends, competitor analysis, customer sentiment, and pricing information.</li><li><strong>Lead Generation:</strong> Web scraping can be used to extract contact information from websites, such as email addresses or phone numbers, to generate leads for marketing or sales purposes.</li><li><strong>Content Aggregation:</strong> With web scraping, you can aggregate content from various sources and create a centralized database or website. This is useful for news aggregators, job boards, or price comparison <strong>websites.</strong></li><li><strong>Monitoring and Tracking:</strong> Web scraping allows you to monitor changes on websites, track prices of products, or keep an eye on competitors’ activities.</li><li><strong>Research and Analysis</strong></li></ol><h4>How To use web scraping :</h4><p>We will be targeting the website “<a href="https://books.toscrape.com/">https://books.toscrape.com/</a>.&quot;</p><p>To scrape the website “<a href="https://books.toscrape.com/">https://books.toscrape.com/</a>&quot; using Python and BeautifulSoup, you can follow these steps:</p><p>Install the necessary libraries:</p><pre>pip install beautifulsoup4<br>pip install requests</pre><p>This code will print a list of book titles from the homepage of the website “<a href="https://books.toscrape.com/">https://books.toscrape.com/</a>&quot;. You can adapt it to scrape other information or navigate to different pages on the website as needed.</p><pre>import requests<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://books.toscrape.com/&quot;<br><br># Send a GET request to the website and retrieve the HTML content<br>response = requests.get(url)<br>content = response.content<br><br># Create a BeautifulSoup object to parse the HTML content<br>soup = BeautifulSoup(content, &quot;html.parser&quot;)<br><br># Extract the titles of all books on the homepage<br>book_titles = []<br>books = soup.find_all(&quot;article&quot;, class_=&quot;product_pod&quot;)<br>for book in books:<br>    title = book.h3.a[&quot;title&quot;]<br>    book_titles.append(title)<br><br># Print the book titles<br>for title in book_titles:<br>    print(title)</pre><p>Let’s extract the link to each book along with its price. We can also save the data in a CSV file.</p><pre>import csv<br>import requests<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://books.toscrape.com/&quot;<br><br># Send a GET request to the website and retrieve the HTML content<br>response = requests.get(url)<br>content = response.content<br><br># Create a BeautifulSoup object to parse the HTML content<br>soup = BeautifulSoup(content, &quot;html.parser&quot;)<br><br># Extract the titles, links, and prices of all books on the homepage<br>book_data = []<br>books = soup.find_all(&quot;article&quot;, class_=&quot;product_pod&quot;)<br>for book in books:<br>    title = book.h3.a[&quot;title&quot;]<br>    link = url + book.h3.a[&quot;href&quot;]<br>    price = book.find(&quot;p&quot;, class_=&quot;price_color&quot;).text.strip()<br>    book_data.append({&quot;Title&quot;: title, &quot;Link&quot;: link, &quot;Price&quot;: price})<br><br># Export the book data to a CSV file<br>filename = &quot;book_data.csv&quot;<br>with open(filename, mode=&quot;w&quot;, newline=&quot;&quot;, encoding=&quot;utf-8&quot;) as file:<br>    writer = csv.DictWriter(file, fieldnames=[&quot;Title&quot;, &quot;Link&quot;, &quot;Price&quot;])<br>    writer.writeheader()<br>    writer.writerows(book_data)<br><br>print(f&quot;Book data exported to {filename} successfully.&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817d8096e65f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why & What is Axios ? ]]></title>
            <link>https://medium.com/@hamzamakh/why-what-is-axios-7b398dbafce1?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b398dbafce1</guid>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[axios-interceptor]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 14:41:36 GMT</pubDate>
            <atom:updated>2023-06-15T14:41:36.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why &amp; What is Axios ? 🤔</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDb0dQ0LvLgitafNhRzEsA.jpeg" /><figcaption>axios</figcaption></figure><h4>What is Axios</h4><p>Axios is a popular JavaScript library that provides a simple and efficient way to make HTTP requests from web browsers or Node.js applications. It serves as a client-side HTTP client and is widely used for sending asynchronous HTTP requests to a server and handling the responses.</p><blockquote><strong>Here’s why Axios.js is widely used and what it offers:</strong></blockquote><p><strong><em>Ease of Use:</em></strong> Axios.js provides a straightforward and intuitive API for making HTTP requests. It supports various request methods such as GET, POST, PUT, DELETE, and more, making it easy to interact with RESTful APIs or other web services.</p><p><strong><em>Promise-based: </em></strong>Axios.js is built on JavaScript promises, which allow for elegant handling of asynchronous operations. It returns promises for requests, enabling you to use techniques like async/await or chainable .then() and .catch() methods to handle responses.</p><p><strong><em>Browser and Node.js Support:</em></strong> Axios.js is designed to work seamlessly in both web browsers and Node.js environments. This flexibility allows developers to use the same code and API for making HTTP requests across different platforms.</p><p><strong><em>Error Handling:</em></strong> Axios.js includes comprehensive error handling capabilities. It automatically detects HTTP errors (status codes in the 4xx or 5xx range) and rejects the promise, allowing you to handle errors easily.</p><p><strong><em>Interceptors:</em></strong> Axios.js provides interceptors that allow you to intercept and modify requests or responses globally. Interceptors are powerful for tasks like adding headers, handling authentication, or handling common errors at a centralized level.</p><p><strong><em>Canceling Requests:</em></strong> Axios.js allows you to cancel requests using cancel tokens. This feature is helpful when you need to abort an ongoing request or cancel multiple requests at once.</p><p><strong><em>Progress Tracking:</em></strong> Axios.js supports progress tracking for requests that involve file uploads or large data transfers. It provides progress events that you can use to track the upload or download progress and display it to the user.</p><h4><strong>To use Axios.js in your JavaScript code , you’ll need to follow these steps:</strong></h4><ol><li>Axios.js can be installed via npm or yarn. Open your terminal and run the following command:</li></ol><pre> npm install axios // using npm <br> yarn add axios    // using yarn</pre><p>2. Import Axios: In your JavaScript file, import Axios using the require or import statement:</p><pre>// Using require <br>const axios = require(&#39;axios&#39;);  <br>// Using import <br>import axios from &#39;axios&#39;;</pre><p>3. Making a GET Request: To make a GET request to a server, use the axios.get() method. Provide the URL you want to send the request to as the argument:</p><pre>axios.get(&#39;https://dummyjson.com/carts&#39;)<br>  .then(response =&gt; {<br>    // Handle the response data<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle any errors<br>    console.error(error);<br>  });</pre><p>4. Making Other Types of Requests: Axios supports various HTTP request methods such as POST, PUT, DELETE, etc. You can use the corresponding methods (axios.post(), axios.put(), axios.delete()) and provide the URL and data as arguments. For example:</p><pre>// POST request<br>axios.post(&#39;https://api.example.com/data&#39;, { name: &#39;John&#39;, age: 25 })<br>  .then(response =&gt; {<br>    // Handle the response<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle any errors<br>    console.error(error);<br>  });</pre><p>5- Customizing Requests: Axios allows you to customize requests by providing additional configuration options. For example, you can set headers, send request data in different formats (JSON, form data, etc.), and more. Here’s an example:</p><pre>axios.post(&#39;https://api.example.com/data&#39;, { name: &#39;John&#39;, age: 25 }, {<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>})<br>  .then(response =&gt; {<br>    // Handle the response<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    // Handle any errors<br>    console.error(error);<br>  });</pre><h4>How us Interceptors in axios</h4><p>Interceptors in Axios.js allow you to intercept and modify HTTP requests or responses globally before they are handled by your application.</p><p>To use interceptors in Axios.js, you can follow the steps below:</p><ol><li>Request Interceptors: Request interceptors are used to modify or handle requests before they are sent. You can add a request interceptor using the axios.interceptors.request.use() method. Here&#39;s an example:</li></ol><pre>// Add a request interceptor<br>axios.interceptors.request.use(<br>  config =&gt; {<br>    // Modify the request config<br>    config.headers.Authorization = &#39;Bearer your_token_here&#39;;<br>    return config;<br>  },<br>  error =&gt; {<br>    // Handle the request error<br>    return Promise.reject(error);<br>  }<br>);</pre><p>In the above example, the request interceptor adds an authorization header to every outgoing request by modifying the request configuration (config).</p><p>this is very helpful when you have many request to treat , you can add an authorization header to each of them . here an example how i use it in one of my project :</p><pre>import axios from &#39;axios&#39;;<br>import secureLocalStorage from &#39;react-secure-storage&#39;;<br>const API = axios.create({ baseURL: &#39;http://localhost:5000&#39; })<br><br>// intercept requests  before they are handled by then or catch<br>API.interceptors.request.use((req)=&gt; {<br>    if(secureLocalStorage.getItem(&#39;token&#39;))  {<br>         req.headers.authorization = `Bearer ${secureLocalStorage.getItem(&#39;token&#39;)}`<br>    }<br>    return req ;<br>})<br><br><br>export const fetchRooms = (userId) =&gt; API.get(`/rooms/${userId}`); <br>export const fetchRoom = (id) =&gt; API.get(`/rooms/getRoom/${id}`);  <br>export const fetchRoomsBySearch = (SearchQuery) =&gt; API.get(`/rooms/getRooms/search?searchQuery=${SearchQuery.search || &#39;none&#39;}&amp;tags=${SearchQuery.tags}&amp;userId=${SearchQuery.userId}&amp;isProfesseur=${SearchQuery.isProfesseur}`);<br>export const createRoom = (formData) =&gt; API.post(&#39;/rooms/createRoom&#39;, formData);<br>export const joinRoom = (formData) =&gt; API.post(&#39;/rooms/rejoindre&#39;, formData);<br>export const updateCour = (id, updatedCour) =&gt; API.patch(`/cours/${id}`, updatedCour);<br>export const addChapitre = (formData) =&gt; API.post(`/rooms/addChapitre`, formData);<br><br>export const fetchChapitre = (id) =&gt; API.get(`/chapitres/${id}`);<br>export const deleteChapitre = (data) =&gt; API.post(`/chapitres/delete`, data);<br>export const updateChapitre = (data) =&gt; API.patch(`/chapitres/update`, data);<br><br>export const consultChapitreByEtudiant = (data) =&gt; API.post(`/rooms/consulter`, data);<br>export const deleteEtudiants = (data) =&gt; API.post(`/rooms/deleteEtudiants`, data);<br><br>export const askfor_new_codeRoom = (idRoom) =&gt; API.patch(`/rooms/askfor_new_codeRoom`, idRoom);<br>export const updateTheme = (data) =&gt; API.put(`/cours/updateTheme`, data);<br>export const fetchThemes = () =&gt; API.get(`/cours/all/themes`);<br><br>export const addComment = (data) =&gt; API.post(`/rooms/addComment`,data);<br>export const getComments = (id) =&gt; API.get(`/rooms/getComments/${id}`);<br>export const deleteComment = (id) =&gt; API.delete(`/rooms/deleteComment/${id}`);<br><br>export const deleteComments_ByIdChapitre = (id) =&gt; API.delete(`/rooms/deleteComments/${id}`);<br><br><br>export const signIn = (formData) =&gt; API.post(`/users/signin`, formData);<br>export const signUp = (formData) =&gt; API.post(`/users/signup`, formData);</pre><p>If you are curious , you can check the full code of the project <a href="https://github.com/hamzamak/classroom-clone"><strong>here</strong></a>.</p><p>2. Response Interceptors: Response interceptors are used to modify or handle responses before they are passed to your application. You can add a response interceptor using the axios.interceptors.response.use() method. Here&#39;s an example:</p><pre>// Add a response interceptor<br>axios.interceptors.response.use(<br>  response =&gt; {<br>    // Modify the response data<br>    response.data = response.data.results;<br>    return response;<br>  },<br>  error =&gt; {<br>    // Handle the response error<br>    return Promise.reject(error);<br>  }<br>);</pre><p>In the above example, the response interceptor modifies the response data by extracting the results property from the response object before passing it to your application.</p><h4>Conclusion:</h4><p>Axios.js has gained popularity in the JavaScript ecosystem due to its simplicity, versatility, and wide range of features. It has become the go-to choice for many developers when it comes to making HTTP requests in JavaScript applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b398dbafce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typewriter Effect in React]]></title>
            <link>https://medium.com/@hamzamakh/typewriter-effect-in-react-a103a4f385c9?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/a103a4f385c9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typewriter]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 11:21:40 GMT</pubDate>
            <atom:updated>2023-06-15T11:21:40.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFI2wLnf1SG_V68lkmKK7w.jpeg" /></figure><p>To create a Typewriter effect in React, you can use the useState and useEffect hooks to manage the state and timing of the effect. Here’s an example of how you can implement it:</p><p>first let’s create a custom React hook named <strong><em>‘useTypewriter’ .</em></strong></p><pre>import  { useState, useEffect } from &#39;react&#39;;<br><br>const useTypewriter = (text, speed = 50) =&gt; {<br>  const [displayText, setDisplayText] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    let i = 0;<br>    const typingInterval = setInterval(() =&gt; {<br>      if (i &lt; text.length) {<br>        setDisplayText(prevText =&gt; prevText + text.charAt(i));<br>        i++;<br>      } else {<br>        clearInterval(typingInterval);<br>      }<br>    }, speed);<br><br>    return () =&gt; {<br>      clearInterval(typingInterval);<br>    };<br>  }, [text, speed]);<br><br>  return displayText;<br>};<br></pre><p>Next , we’re using a functional component named Typewriter. It takes two props: text and speed. Inside the component, the useTypewriter hook is used to get the displayText state.</p><pre>const Typewriter = ({ text, speed }) =&gt; {<br>  const displayText = useTypewriter(text, speed);<br><br>  return &lt;p&gt;{displayText}&lt;/p&gt;;<br>};<br><br>export default Typewriter;</pre><p>Now let’s test it :</p><pre> &lt;Typewriter text= &quot;This is Working Fine !!&quot;/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*QSpJEj82ZrqO8W8zLAr-Bg.gif" /></figure><p><strong>I hope this helps! 😉</strong></p><p>For more projects . Follow me on <a href="https://github.com/hamzamak"><strong>github </strong></a>🙃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a103a4f385c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which is better Tailwind CSS or Bootstrap?]]></title>
            <link>https://medium.com/@hamzamakh/which-is-better-tailwind-css-or-bootstrap-d20336182ebc?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20336182ebc</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[bootstrap]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 18:51:00 GMT</pubDate>
            <atom:updated>2023-06-14T18:51:00.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*R6Ps7C3R5exnXd7w4RrRaQ.jpeg" /><figcaption>Tailwind VS Bootstrap</figcaption></figure><p>The choice between Tailwind CSS and Bootstrap ultimately depends on your specific needs and preferences. Both frameworks are popular choices for building responsive and visually appealing websites, but they have different approaches and philosophies.</p><p><strong>Bootstrap</strong> is a comprehensive CSS framework that provides a set of pre-designed components and a grid system. It offers a more opinionated and structured approach to web development, with ready-to-use styles and components that can be easily customized. <strong>Bootstrap</strong> has been around for a longer time and has a large community, extensive documentation, and a wide range of themes and plugins available.</p><p>On the other hand, <strong>Tailwind CSS</strong> takes a different approach by providing a utility-first methodology. Instead of pre-designed components, Tailwind CSS offers a collection of small utility classes that you can combine to build your own custom designs. This gives you more flexibility and control over the styling of your project, but it also requires more manual configuration and customization.</p><blockquote><strong>Here are some factors to consider when choosing between Tailwind CSS and Bootstrap:</strong></blockquote><p><strong>Difference #1:</strong><br>Tailwind CSS offers a wide range of pre-designed widgets and components that can be used to build a website from scratch, providing fast UI development. In contrast, Bootstrap comes with a comprehensive set of pre-styled responsive and mobile-first components, offering a defined UI kit for building websites.</p><p><strong>Difference #2:</strong><br>Tailwind CSS allows for a high level of customization, enabling developers to create unique and highly tailored website designs. On the other hand, websites created with Bootstrap are known for their responsiveness and polished design, but they can sometimes appear generic and similar due to the framework’s recognizable styles.</p><p><strong>Difference #3:</strong><br>Tailwind CSS relies on a utility-first approach, utilizing a vast collection of utility classes that can be combined to create a clean and flexible user interface. This approach gives developers more flexibility and control over the styling of their websites, allowing for a greater degree of uniqueness. In contrast, Bootstrap follows a more opinionated approach with pre-defined styles and components, resulting in websites that often follow a similar pattern and look similar to other Bootstrap-based sites.</p><p><strong>Difference #4</strong>:<br>Tailwind CSS encourages a &quot;write your own CSS&quot; approach, where developers can easily create custom styles using utility classes. This allows for a highly modular and scalable CSS architecture. Bootstrap, on the other hand, provides a set of pre-designed CSS classes and components, which can be convenient for rapid prototyping but might require additional customization for more specific design needs.</p><p><strong>Difference #5:</strong><br>Tailwind CSS has a smaller file size compared to Bootstrap. Tailwind CSS follows a utility-based approach where only the classes that are used in the project are included in the final CSS file, resulting in a smaller overall footprint. Bootstrap, being a more comprehensive framework, includes a larger set of CSS and JavaScript files, which can increase the size of the project.</p><p><strong>Difference #6:</strong><br>Tailwind CSS offers a more developer-centric experience with its utility classes and utility-first philosophy. It provides a highly customizable and flexible toolkit that developers can leverage to build unique designs. On the other hand, Bootstrap aims to provide a more out-of-the-box solution, catering to developers who prefer a structured and opinionated framework that streamlines the development process.</p><p><strong>Difference #7:</strong><br>Tailwind CSS integrates seamlessly with other JavaScript frameworks and libraries, allowing developers to use it alongside tools like React, Vue.js, or Angular. It provides a solid foundation for building UI components within these frameworks. While Bootstrap can also be used with other frameworks, its components and JavaScript plugins are primarily designed to work within the Bootstrap ecosystem.</p><p><strong>Difference #8:</strong><br>Tailwind CSS has a less opinionated design aesthetic, allowing developers to create visually distinct and unique designs. Bootstrap, on the other hand, has a recognizable and consistent design language, making it a popular choice for projects where maintaining a consistent visual style across pages is important.</p><h3>Summary :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*9kWIQUZAJPdUjM-coXxDhg.jpeg" /></figure><h3>Conclusion</h3><p>Ultimately, both frameworks have their strengths and are widely used in the industry. It’s recommended to evaluate your project requirements, consider your familiarity with CSS, and experiment with both frameworks to see which one aligns better with your workflow and preferences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20336182ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up an Express Server for OpenAI API Integration]]></title>
            <link>https://medium.com/@hamzamakh/setting-up-an-express-server-for-openai-api-integration-3c3f4388ffe9?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c3f4388ffe9</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[astrojs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 16:47:51 GMT</pubDate>
            <atom:updated>2023-06-13T16:50:27.265Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*eZ0zXbEpHru7SymZexpG-Q.jpeg" /><figcaption>Build a app using openai and nodejs</figcaption></figure><p>In this blog post, we will explore a code example that demonstrates how to set up an Express server for integrating with the OpenAI API. This integration allows you to leverage the power of OpenAI’s language models in your applications, enabling you to generate human-like text responses based on user prompts. We will walk through the code step by step, explaining each component and its purpose.</p><blockquote>1- Setup the server :</blockquote><p>You need to have <strong>nodejs </strong>first installed in your computer<strong> , </strong>if you don’t have it , download it here</p><p><a href="https://nodejs.org/en/download">Node.js - Download Node.js®</a></p><p>You can create a working folder for the project , I’m gonna named it ‘‘server’’, then change into this newly created directory using <em>cd command </em>in your terminal</p><pre>mkdir server<br>cd server  </pre><p>Running this command initializes your project:</p><pre>npm init -y</pre><p>the -y flag is used with the npm init command to automatically generate a package.json file without any user prompts. It instructs npm to use default values for all the prompts typically displayed during the initialization process.</p><p>Next let’s create the default entry file index.js in <em>server </em>directory</p><blockquote>2- Installing the dependencies:</blockquote><pre>npm i express cors openai nodemon dotenv</pre><blockquote>3- Creating a Simple express app :</blockquote><pre>import express from &#39;express&#39;<br>import cors from &#39;cors&#39;<br>const app = express()<br>app.use(cors())<br>app.use(express.json())<br><br>app.get(&#39;/&#39;, async (req, res) =&gt; {<br>  res.status(200).send({<br>    message: &#39;Hello from ChatGpt!&#39;<br>  })<br>})<br>app.listen(5000, () =&gt; console.log(&#39;AI server started on http://localhost:5000&#39;))</pre><p>Note :</p><p>I’m using ES6 module syntax for the imports , to do that juste go to package.json and add :</p><pre>&quot;type&quot;: &quot;module&quot;,</pre><blockquote>4 - Configure openai connection</blockquote><p>in index.js file :</p><pre>import * as dotenv from &#39;dotenv&#39;<br>import { Configuration, OpenAIApi } from &#39;openai&#39;<br><br>dotenv.config()<br><br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>const openai = new OpenAIApi(configuration);</pre><p>Here, we create a new instance of the Configuration class and provide the OpenAI API key as the apiKey parameter. The API key is retrieved from the environment variables using process.env.OPENAI_API_KEY.</p><p>create a <strong>.env </strong>file , add this line and replace it with your api key</p><pre>OPENAI_API_KEY=your_openai_key</pre><p>To create a new api key , visit the link bellow :</p><p><a href="https://openai.com/blog/openai-api">OpenAI API</a></p><p>then Go to View API keys</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxTCh0xliw-_eiP0HZkrZQ.png" /><figcaption>OpenAi plateform</figcaption></figure><p>Then Create new secret key , copy and paste it to your .env file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KweNZgu9DkptHMGQRn_Rdw.png" /><figcaption>API Keys</figcaption></figure><blockquote>4- Handle the chat request</blockquote><p>We define another route handler for POST requests to the root URL (‘/’). When a POST request is received, the server expects a JSON object in the request body with a “prompt” field. This prompt is the input provided by the user. The server then makes a call to the OpenAI API using the ‘openai.createCompletion()’ method, passing the prompt and additional parameters for model configuration. The API responds with a generated text, and the server sends this response back to the client.</p><pre>app.post(&#39;/&#39;, async (req, res) =&gt; {<br>  try {<br>    const prompt = req.body.prompt;<br><br>    const response = await openai.createCompletion({<br>      model: &quot;text-davinci-003&quot;,<br>      prompt: `${prompt}`,<br>      temperature: 0, // Higher values means the model will take more risks.<br>      max_tokens: 3000, // The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).<br>      top_p: 1, // alternative to sampling with temperature, called nucleus sampling<br>      frequency_penalty: 0.5, // Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model&#39;s likelihood to repeat the same line verbatim.<br>      presence_penalty: 0, // Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model&#39;s likelihood to talk about new topics.<br>    });<br><br>    res.status(200).send({<br>      bot: response.data.choices[0].text<br>    });<br>  <br>  } catch (error) {<br>    console.error(error)<br>    res.status(500).send(error || &#39;Something went wrong&#39;);<br>  }</pre><blockquote><strong>Full-code :</strong></blockquote><p>index.js file :</p><pre>import express from &#39;express&#39;<br>import cors from &#39;cors&#39;<br>import * as dotenv from &#39;dotenv&#39;<br>import { Configuration, OpenAIApi } from &#39;openai&#39;<br><br>dotenv.config()<br><br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>const openai = new OpenAIApi(configuration);<br><br>const app = express()<br>app.use(cors())<br>app.use(express.json())<br><br>app.get(&#39;/&#39;, async (req, res) =&gt; {<br>  res.status(200).send({<br>    message: &#39;Hello from ChatGpt!&#39;<br>  })<br>})<br><br>app.post(&#39;/&#39;, async (req, res) =&gt; {<br>  try {<br>    const prompt = req.body.prompt;<br><br>    const response = await openai.createCompletion({<br>      model: &quot;text-davinci-003&quot;,<br>      prompt: `${prompt}`,<br>      temperature: 0, // Higher values means the model will take more risks.<br>      max_tokens: 3000, // The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).<br>      top_p: 1, // alternative to sampling with temperature, called nucleus sampling<br>      frequency_penalty: 0.5, // Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model&#39;s likelihood to repeat the same line verbatim.<br>      presence_penalty: 0, // Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model&#39;s likelihood to talk about new topics.<br>    });<br><br>    res.status(200).send({<br>      bot: response.data.choices[0].text<br>    });<br>  <br>  } catch (error) {<br>    console.error(error)<br>    res.status(500).send(error || &#39;Something went wrong&#39;);<br>  }<br>})<br><br>app.listen(5000, () =&gt; console.log(&#39;AI server started on http://localhost:5000&#39;))</pre><blockquote><strong>5- Code Source :</strong></blockquote><p>code source : <a href="https://github.com/hamzamak/chatgpt-clone">https://github.com/hamzamak/chatgpt-clone</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3J3N3lDWxdWoAYz1mOwteA.gif" /><figcaption>Demo App</figcaption></figure><blockquote><strong>6- Additional ressource:</strong></blockquote><p>If you want to see An example of image generation using openai For</p><p>Mobile : <a href="https://github.com/hamzamak/dall-e-mobile">https://github.com/hamzamak/dall-e-mobile</a></p><p>Web : <a href="https://github.com/hamzamak/dalle-project">https://github.com/hamzamak/dalle-project</a></p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c3f4388ffe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Astro.js]]></title>
            <link>https://medium.com/@hamzamakh/introduction-to-astro-js-78e421b0548b?source=rss-4122279b8d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e421b0548b</guid>
            <category><![CDATA[astrojs]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Hamza Makhkhas]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 22:55:32 GMT</pubDate>
            <atom:updated>2023-06-10T22:56:43.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*APfJddi0t6edauHSFHiQ0A.png" /></figure><h3><strong>What is Astro.js</strong></h3><p>Astro.js is a modern front-end framework for building static websites and web applications. It allows you to write your website using components and bring in data from various sources, such as APIs or Markdown files. Astro.js takes a différent approach compared to traditional front-end frameworks like React or Vue.</p><h3><strong>Why Use Astro?</strong></h3><ul><li>Performance: Astro.js generates static HTML, CSS, and JavaScript files, which can be served directly from a CDN or a static file server. This approach improves website performance by reducing the time it takes to load and render pages. Users experience faster load times, which can lead to better engagement and improved SEO rankings.</li><li>Flexibility: Astro.js allows you to use components from different JavaScript frameworks like React, Vue, or Svelte within the same project. This flexibility enables you to leverage the strengths of various frameworks and libraries, making it easier to reuse existing code and integrate with third-party tools.</li><li>Simplified Development: With Astro.js, you can build your website using a component-based approach, which enhances code reusability and maintainability. The framework streamlines the development process by providing a unified syntax for building components, managing styles, and handling data sources.</li><li>Incremental Adoption: If you have an existing project built with another front-end framework, Astro.js allows for incremental adoption. You can gradually migrate parts of your application to Astro.js without needing to rewrite everything from scratch.</li><li>Data Integration: Astro.js supports various data integration options, including fetching data from APIs and using static data sources. It also provides serverless functions that enable dynamic data fetching during the build process. This flexibility allows you to integrate data from different sources seamlessly.</li><li>SEO-friendly: Static sites generated by Astro.js are highly SEO-friendly since search engines can easily crawl and index the static HTML content. This can improve your website’s visibility in search engine results and drive more organic traffic.</li><li>Developer Community and Ecosystem: Astro.js has an active and growing developer community, providing support, tutorials, and resources. The ecosystem around Astro.js is evolving, with plugins and extensions being developed to extend its capabilities.</li></ul><h3>The power of astro island ?</h3><p>Astro Islands, also known as Component Islands, are a web architecture pattern introduced by Astro. This pattern involves creating interactive UI components within an otherwise static HTML page. Each island represents an isolated and interactive component, while the surrounding content remains static.</p><p>Astro allows you to use various UI frameworks like React, Preact, Svelte, Vue, SolidJS, AlpineJS, or Lit to render these islands in the browser. You have the flexibility to mix and match different frameworks on the same page or use your preferred framework.</p><p>example using react component :</p><p>first you need to integrate react ,</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6484e559bda36b001315e226&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2F6484e559bda36b001315e226&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3403e02e30b46f4d1dbdd01a9824c6/href">https://medium.com/media/0d3403e02e30b46f4d1dbdd01a9824c6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6484fbf5bda36b001315e228&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Freact-component-react-js%2F6484fbf5bda36b001315e228&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="231" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb1339cf3b156804225a5a7d6774054d/href">https://medium.com/media/fb1339cf3b156804225a5a7d6774054d/href</a></iframe><p>This component represents your interactive island.</p><p>Create an Astro page: Inside the src/pages directory, open the index.astro file and import your React component:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6484fc7fbda36b001315e22a&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fastro-react-js%2F6484fc7fbda36b001315e22a&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="127" frameborder="0" scrolling="no"><a href="https://medium.com/media/83167589e2cbe0ce6418911d5ad0ce52/href">https://medium.com/media/83167589e2cbe0ce6418911d5ad0ce52/href</a></iframe><h3>Comparing Astro.js with Other Frameworks:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgxkrfMGmQ9Vwp-uMtrQxQ.png" /><figcaption>Astro optimizes your website like no other framework can.</figcaption></figure><p>Good performance is always important, but it is especially critical for content-focused websites. It has been well-proven that poor performance loses you engagement, conversions, and money. For example:</p><p>Every 100ms faster → 1% more conversions (Mobify, earning +$380,000/yr)<br>50% faster → 12% more sales (AutoAnything)<br>20% faster → 10% more conversions (Furniture Village)<br>40% faster → 15% more sign-ups (Pinterest)<br>850ms faster → 7% more conversions (COOK)<br>Every 1 second slower → 10% fewer users (BBC)<br>In many web frameworks, it is easy to build a website that looks great during development only to load painfully slow once deployed. JavaScript is often the culprit, since users’ phones and lower-powered devices rarely match the speed of a developer’s laptop.</p><blockquote><strong><em>An Astro website can load 40% faster with 90% less JavaScript than the same site built with the most popular React web framework.</em></strong></blockquote><h3>Conclusion</h3><p>Astro is an all-in-one web framework that comes with everything you need to build a website. Astro includes a component syntax, file-based routing, asset handling, a build process, bundling, optimizations, data-fetching, and more. You can build great websites without ever reaching outside of Astro’s core feature set.</p><p>If you need more control, you can extend Astro with over 100+ integrations like React, Svelte, Vue, Tailwind CSS, MDX, image optimizations, and more. Connect your favorite CMS or deploy to your favorite host with just a single command.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e421b0548b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>