<?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 Tókos Bence on Medium]]></title>
        <description><![CDATA[Stories by Tókos Bence on Medium]]></description>
        <link>https://medium.com/@tokosbex?source=rss-a94880eb88a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rA5O59RdlGqtz171jLvjFw.jpeg</url>
            <title>Stories by Tókos Bence on Medium</title>
            <link>https://medium.com/@tokosbex?source=rss-a94880eb88a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:26:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tokosbex/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[Docker for AI: GPU Acceleration and Task Queuing with Celery]]></title>
            <link>https://medium.com/@tokosbex/docker-for-ai-gpu-acceleration-and-task-queuing-with-celery-ae254059b92e?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae254059b92e</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 22:14:33 GMT</pubDate>
            <atom:updated>2024-06-18T22:14:33.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl1-aD5KpQ4-SoDz17ghQQ.jpeg" /><figcaption>Docker &amp;&amp; GPU acceleration</figcaption></figure><p>These days, AI is permeating every space and project, gradually but consistently taking over simple automation jobs. AI is incredibly useful when we want to build something valuable, and for faster development, we aim to automate certain tasks. In the context of development flow, at the end of the process, we need to use a pipeline for deployment. One of the best ways to achieve this is by dockerizing the application and deploying it from that Docker image.</p><p>In AI model development, using hardware acceleration, specifically GPUs, becomes essential at some point. Dockerizing a simple app is not particularly challenging, but accessing hardware resources requires extra configuration or special images. I struggled for a long time to run a simple Flask app that uses a basic LLM model and accesses the GPU. Therefore, I want to share the solution I found after some research.</p><p>In my app, I’m also using Celery for queuing the AI tasks because the user needs to wait for the result for a certain amount of time. But what is Celery?</p><p>Celery is an asynchronous task queue/job queue that is based on distributed message passing. It is focused on real-time operation but supports scheduling as well. The execution units, called tasks, are executed concurrently on one or more worker servers using multiprocessing, eventlet, or gevent. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).</p><p>Using Celery can significantly improve the responsiveness of your application by offloading long-running tasks to the background. This way, your web application can handle multiple requests without getting blocked by time-consuming processes. Celery is commonly used in conjunction with message brokers like RabbitMQ or Redis, which handle the task distribution between workers.</p><p><strong>Let’s see the docker file!</strong></p><pre># Use a Python base image with CUDA support<br>FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04 <br><br># Install Python, Git, and additional dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y python3-pip<br><br>RUN apt-get update &amp;&amp; \<br>    DEBIAN_FRONTEND=noninteractive apt-get install -y \<br>    python3.9 \<br>    python3-pip \<br>    curl \<br>    gnupg \<br>    libgl1-mesa-glx \<br>    libglib2.0-0 \    <br>    libcudnn8 \<br>    libcudnn8-dev \<br>    git \<br>    wget \<br>    tesseract-ocr \<br>    tesseract-ocr-eng \<br>    poppler-utils \ <br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Set working directory<br>WORKDIR /app/microservice<br><br># Copy requirements.txt<br>COPY requirements.txt .<br><br># Install Python dependencies<br>RUN pip install --upgrade pip &amp;&amp; \<br>    pip install -r requirements.txt <br><br># Copy the rest of the microservice files<br>COPY . .<br><br># Expose port<br>EXPOSE 5002<br><br># Start Flask application and Celery worker processes<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;celery -A app.celery_client worker -l info -P solo &amp; flask run -h 0.0.0.0 -p 5002&quot;]</pre><ol><li><strong>Base Image:</strong></li></ol><pre>FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04</pre><p>This line sets the base image to an NVIDIA CUDA runtime with cuDNN support, based on Ubuntu 22.04. This image is optimized for running applications that require GPU acceleration.</p><p>2.<strong> Install Python, Git, and Additional Dependencies:</strong></p><pre>RUN apt-get update &amp;&amp; apt-get install -y python3-pip</pre><p>This command updates the package list and installs python3-pip.</p><pre>RUN apt-get update &amp;&amp; \<br>    DEBIAN_FRONTEND=noninteractive apt-get install -y \<br>    python3.9 \<br>    python3-pip \<br>    curl \<br>    gnupg \<br>    libgl1-mesa-glx \<br>    libglib2.0-0 \    <br>    libcudnn8 \<br>    libcudnn8-dev \<br>    git \<br>    wget \<br>    tesseract-ocr \<br>    tesseract-ocr-eng \<br>    poppler-utils \ <br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>This command installs several packages:</p><ul><li>python3.9 and python3-pip: Python 3.9 and the pip package manager.</li><li>curl and gnupg: Tools for downloading files and managing GPG keys.</li><li>libgl1-mesa-glx and libglib2.0-0: Libraries required for OpenGL and GLib.</li><li>libcudnn8 and libcudnn8-dev: Libraries and development files for cuDNN.</li><li>git and wget: Tools for downloading and managing code repositories.</li><li>tesseract-ocr and tesseract-ocr-eng: OCR tool and English language data.</li><li>poppler-utils: Utilities for handling PDF files.</li></ul><p>The last two are not necessary because I’m using those tools! :)</p><p>3. <strong>Set Working Directory:</strong></p><pre>WORKDIR /app/microservice</pre><p>This sets the working directory inside the container to /app/microservice.</p><p>4.<strong> Copy requirements.txt:</strong></p><pre>COPY requirements.txt .</pre><p>This copies the requirements.txt file from your local machine to the container.</p><p>5.<strong> Install Python Dependencies:</strong></p><pre>RUN pip install --upgrade pip &amp;&amp; \<br>    pip install -r requirements.txt</pre><p>This upgrades pip and installs the Python dependencies listed in requirements.txt.</p><p>6. <strong>Copy the Rest of the Microservice Files:</strong></p><pre>COPY . .</pre><p>This copies all the remaining application files from your local machine to the container.</p><p>7.<strong> Expose Port:</strong></p><pre>EXPOSE 5002</pre><p>This tells Docker to expose port 5002, which is where the Flask application will run.</p><p>8. <strong>Start Flask Application and Celery Worker Processes:</strong></p><pre>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;celery -A app.celery_client worker -l info -P solo &amp; flask run -h 0.0.0.0 -p 5002&quot;]</pre><p>This command starts the Celery worker and the Flask application:</p><ul><li>celery -A app.celery_client worker -l info -P solo starts the Celery worker for task processing. (If you are not using Celery, you can use this command (additional configuration in the app is needed if you want to use Celery:</li></ul><pre>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;flask run -h 0.0.0.0 -p 5002&quot;]</pre><ul><li>flask run -h 0.0.0.0 -p 5002 starts the Flask application, making it accessible on all network interfaces (0.0.0.0) on port 5002.</li></ul><p>In summary, this Dockerfile sets up a container environment with all necessary dependencies, including CUDA and cuDNN support for GPU acceleration, and prepares the application to run a Flask web server and a Celery worker for handling asynchronous tasks.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, leveraging Docker with CUDA support provides a robust solution for deploying AI applications that require GPU acceleration. By containerizing the application, we ensure a consistent and replicable environment, which simplifies the deployment process and enhances scalability. Additionally, integrating Celery for task queuing allows for efficient handling of long-running AI tasks, improving the responsiveness and overall performance of the application.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae254059b92e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes and Docker Deployment on Google Cloud SDK]]></title>
            <link>https://medium.com/@tokosbex/kubernetes-and-docker-deployment-on-google-cloud-sdk-f21a123d8ebe?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21a123d8ebe</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 18:03:16 GMT</pubDate>
            <atom:updated>2024-06-18T18:03:16.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OB9_JogQn0ITVMkPjfXraA.jpeg" /><figcaption>GKE deployment with docker</figcaption></figure><p>These days, it is crucial to create good and effective development pipelines. Cloud platforms are essential for development, and that’s why I want to show you a quick overview of how to create a simple deployment flow using Google Cloud with Google Kubernetes Engine (GKE).</p><h3>Initial setup</h3><p>First, you need to create a cluster. You can easily do this using the GUI. After creating the cluster, check the Cloud Console to ensure you are using the correct context. If you haven’t installed the kubectl component yet, you need to install it first:</p><pre>gcloud components install kubectl</pre><p>You can find more useful information <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl"><strong>here!</strong></a></p><p>Ensure the correct cluster and namespace context:</p><ul><li>gcloud container clusters get-credentials your-cluster-name — zone=your-cluster-zone</li><li>kubectl config get-contexts</li><li>kubectl config set-context — current — namespace=your-namespace</li><li>kubectl config view</li></ul><h3>Create Name Space and Service Account</h3><p>After you create the cluster, your application may need access to other Google Cloud solutions. To manage this easily, you can create a namespace and a service account, which you can then annotate with the IAM service account.</p><pre>kubectl create ns {NAMESPACE}<br>kubectl create serviceaccount {SERVICE_ACCOUNT_NAME -n NAMESPACE}</pre><p><strong>Annotate Service Account</strong></p><pre>kubectl annotate sa {SERVICE_ACCOUNT_NAME} iam.gke.io/gcp-service-account={GCP_SERVICE_ACCOUNT} -n {NAMESPACE}</pre><p><strong>Add Roles</strong></p><pre>gcloud iam service-accounts add-iam-policy-binding --role<br>roles/iam.workloadIdentityUser --member<br>&quot;serviceAccount: YOUR_PROJECT_NAME.svc.id.goog[YOUR_NAMESPACE/YOUR_SERVICE_ACCOUNT]&quot; {SERVICE_ACCOUNT_NAME}@{YOUR_PROJECT_NAME}.iam.gserviceaccount.com</pre><p>Now that we have successfully configured the cluster, we can set up the artifact repository.</p><h3>Configure Docker Repository in Google Cloud Shell</h3><ul><li>gcloud artifacts repositories describe {your_repository_name} — location={repository_location}</li></ul><p>If you have an artifact repository, there’s nothing more you need to do. When you build the Docker image, use your repository location, your Google Cloud project name, and your repository name. Additionally, you can add versioning at the end. Do the same when you push the Docker image.</p><h3>Build and Tag Docker Image</h3><ul><li>docker build -t {repository_location}-docker.pkg.dev/YOUR_PROJECT_NAME/YOUR_REPO_NAME/FILE_NAME:vX .</li></ul><h3>Push Docker Image to Artifact Registry</h3><ul><li>docker push {repository_location}-docker.pkg.dev/YOUR_PROJECT_NAME/YOUR_REPO_NAME/FILE_NAME:vX</li></ul><p>Alright, we are done with the setup. Now, for the deployment, we will create a deployment YAML file. Here we have some basic configurations, but what is important are the Docker image and the environment variables. You can add as many environment variables as you need.</p><h3>Deployment yaml</h3><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {NAME}<br>  labels:<br>    app: {NAME}<br>spec:<br>  progressDeadlineSeconds: 200<br>  replicas: 3<br>  revisionHistoryLimit: 10<br>  selector:<br>    matchLabels:<br>      app: {NAME}<br>  strategy:<br>    rollingUpdate:<br>      maxSurge: 25%<br>      maxUnavailable: 25%<br>    type: RollingUpdate<br>  template:<br>    metadata:<br>      creationTimestamp: null<br>      labels:<br>        app: {NAME}<br>    spec:<br>      serviceAccountName: {YOUR_SERVICE_ACCOUNT}<br>      containers:<br>        - image: {YOUR_IMAGE_SOURCE}<br>          imagePullPolicy: IfNotPresent<br>          name: {NAME}-sha256-1<br>          resources:<br>            limits:<br>              cpu: 500m<br>              ephemeral-storage: 1Gi<br>              memory: 2Gi<br>            requests:<br>              cpu: 500m<br>              ephemeral-storage: 1Gi<br>              memory: 2Gi<br>          securityContext:<br>            capabilities:<br>              drop:<br>                - NET_RAW<br>          terminationMessagePath: /dev/termination-log<br>          terminationMessagePolicy: File<br>          env:<br>            - name: ENV_NAME<br>              value: ENV_VALUE<br>      dnsPolicy: ClusterFirst<br>      restartPolicy: Always<br>      schedulerName: default-scheduler<br>      securityContext:<br>        seccompProfile:<br>          type: RuntimeDefault<br>      terminationGracePeriodSeconds: 30<br>      tolerations:<br>        - effect: NoSchedule<br>          key: kubernetes.io/arch<br>          operator: Equal<br>          value: amd64</pre><h3>General Structure</h3><p><strong>apiVersion: apps/v1</strong></p><ul><li>Specifies the version of the Kubernetes API you’re using to create this object. Here, it’s apps/v1, which is appropriate for deployments.</li></ul><p><strong>kind: Deployment</strong></p><ul><li>Specifies the type of Kubernetes resource you’re creating, which is a Deployment in this case.</li></ul><p><strong>metadata</strong></p><ul><li>name: {NAME} — The name of the Deployment. Replace {NAME} with your desired name.</li><li><strong>labels — </strong>Labels are key-value pairs that are attached to objects, such as pods, to organize and select subsets of objects</li><li><strong>app: {NAME} — </strong>A label named app with a value of {NAME}. This label helps in identifying and selecting the pods that are part of this deployment.</li></ul><h3>spec</h3><ul><li><strong>progressDeadlineSeconds: 200 — </strong>The time in seconds to wait for a deployment to progress before reporting it as failed. Defaults to 600 seconds if not specified.</li><li><strong>replicas: 3 — </strong>Specifies the number of pod replicas to run at any given time. Here, it’s set to 3.</li><li><strong>revisionHistoryLimit: 10 — </strong>The number of old ReplicaSets to retain to allow rollback to previous versions. Here, it keeps the last 10 revisions.</li><li><strong>selector — </strong>Specifies how to identify which pods belong to this deployment.</li><li><strong>app: {NAME} — </strong>Matches pods with the label app set to {NAME}.</li><li><strong>strategy — </strong>Specifies the strategy used to replace old pods by new ones.</li><li><strong>maxSurge: 25% — </strong>The maximum number of pods that can be created over the desired number of pods during the update process.</li><li><strong>maxUnavailable: 25% — </strong>The maximum number of pods that can be unavailable during the update process.</li><li><strong>type: RollingUpdate — </strong>Specifies that the update strategy is a RollingUpdate, which updates pods in a rolling manner.</li></ul><h3>template</h3><ul><li>Describes the pods that will be created.</li><li><strong>creationTimestamp: null — </strong>This field is set to null by default.</li><li><strong>app: {NAME} — </strong>Pods created by this deployment will have the label app set to {NAME}.</li><li><strong>serviceAccountName: {YOUR_SERVICE_ACCOUNT} — </strong>Specifies the service account to be used by the pods. Replace {YOUR_SERVICE_ACCOUNT} with your actual service account name.</li><li><strong>containers — </strong>Describes the container(s) that will be run in the pods.</li><li><strong>image: {YOUR_IMAGE_SOURCE} — </strong>The Docker image to be used for the container. Replace {YOUR_IMAGE_SOURCE} with your actual image source.</li><li><strong>imagePullPolicy: IfNotPresent — </strong>The image pull policy, which indicates to pull the image only if it is not present on the node.</li><li><strong>name: {NAME}-sha256–1 — </strong>The name of the container. Replace {NAME} with your desired name.</li><li><strong>resources — </strong>Specifies the resource requests and limits for the container.</li><li><strong>securityContext — </strong>Security settings for the container.</li><li><strong>NET_RAW — </strong>Drops the NET_RAW capability for the container to enhance security.</li><li><strong>terminationMessagePath: /dev/termination-log — </strong>Path where termination messages are written.</li><li><strong>terminationMessagePolicy: File — </strong>Indicates that the termination message should be retrieved from a file.</li><li><strong>env — </strong>Specifies environment variables for the container.</li><li><strong>name: ENV_NAME</strong></li><li><strong>value: ENV_VALUE — </strong>Adds an environment variable named ENV_NAME with a value of ENV_VALUE. You can add as many environment variables as needed.</li><li><strong>dnsPolicy: ClusterFirst — </strong>Sets the DNS policy for the pod to ClusterFirst, which prioritizes cluster DNS.</li><li><strong>restartPolicy: Always — </strong>Ensures that the pod is restarted automatically if it fails.</li><li><strong>schedulerName: default-scheduler — </strong>Specifies the scheduler to be used for the pod, which is the default scheduler.</li><li><strong>securityContext — </strong>Security settings for the pod.</li><li><strong>type: RuntimeDefault — </strong>Uses the runtime default Seccomp profile for the pod.</li><li><strong>terminationGracePeriodSeconds: 30 — </strong>Grace period for pod termination.</li><li><strong>tolerations — </strong>Allows the pods to be scheduled on nodes with specific taints.</li></ul><h3><strong>Cloud build trigger</strong></h3><pre>steps:<br>  - name: &quot;gcr.io/cloud-builders/docker&quot;<br>    args:<br>      - &quot;build&quot;<br>      - &quot;-t&quot;<br>      - &quot;{PROJECT_LOCATION}-docker.pkg.dev/{PROJECT_NAME}/{FOLDER_NAME}/{IMAGE_NAME}&quot;<br>   - &quot;.&quot;<br>  - name: &quot;gcr.io/cloud-builders/docker&quot;<br>    args:<br>      - &quot;push&quot;<br>      - &quot;{PROJECT_LOCATION}-docker.pkg.dev/{PROJECT_NAME}/{FOLDER_NAME}/{IMAGE_NAME}&quot;</pre><p><strong>Step 1: Build Docker Image</strong></p><ul><li><strong>name: “</strong><a href="http://gcr.io/cloud-builders/docker"><strong>gcr.io/cloud-builders/docker</strong></a><strong>”</strong></li><li>Specifies the Docker builder image provided by Google Cloud, which includes the Docker CLI tools needed to build and push Docker images.</li><li><strong>“build”</strong>: The Docker build command.</li><li><strong>“-t”</strong>: The flag to specify the tag (name) for the Docker image being built.</li><li><strong>“{PROJECT_LOCATION}-docker.pkg.dev/{PROJECT_NAME}/{FOLDER_NAME}/{IMAGE_NAME}”</strong>: The full image name including the Google Artifact Registry location, project name, folder (repository) name, and image name. Replace {PROJECT_LOCATION}, {PROJECT_NAME}, {FOLDER_NAME}, and {IMAGE_NAME} with your actual values.</li><li><strong>“.”</strong>: The context for the Docker build, which is typically the current directory. This means the Docker build command will use the Dockerfile in the current directory to build the image.</li></ul><p><strong>Step 2: Push Docker Image</strong></p><ul><li><strong>name: “</strong><a href="http://gcr.io/cloud-builders/docker"><strong>gcr.io/cloud-builders/docker</strong></a><strong>”</strong></li><li>Again, specifies the Docker builder image provided by Google Cloud for the push command.</li><li><strong>“push”</strong>: The Docker push command, which uploads the built Docker image to the specified repository.</li><li><strong>“{PROJECT_LOCATION}-docker.pkg.dev/{PROJECT_NAME}/{FOLDER_NAME}/{IMAGE_NAME}”</strong>: The full image name that was used during the build step. This should be the same as the tag used in the build command to ensure the correct image is pushed.</li></ul><h3>Applying the Deployment YAML</h3><p>Once you’ve prepared your deployment YAML file, you need to apply it to your Kubernetes cluster. This step will create the deployment, which in turn will manage the pods running your application. Here’s how to do it:</p><ol><li><strong>Save the YAML file</strong>: Ensure your deployment YAML file (e.g., deployment.yaml) is saved and accessible from your terminal.</li><li><strong>Apply the YAML file</strong>: Use the kubectl apply command to apply the deployment configuration to your cluster.</li></ol><pre>kubectl apply -f deployment.yaml</pre><p>This command tells Kubernetes to create the resources defined in your YAML file. Kubernetes will handle the rest, ensuring the specified number of replicas are running, managing updates, and maintaining the desired state.</p><h3>Verify the Deployment</h3><p>After applying the deployment, you can verify that it has been created and is running as expected:</p><ol><li><strong>Check the deployment status</strong>: Use the kubectl get deployments command to check the status of your deployment.</li></ol><pre>kubectl get deployments</pre><p>2. <strong>Check the pods:</strong> Use the kubectl get pods command to list the pods managed by the deployment.</p><pre>kubectl get pods</pre><h3>Conclusion</h3><p>In today’s fast-paced development environment, creating efficient and reliable development pipelines is crucial. Cloud platforms like Google Cloud provide powerful tools to streamline this process. In this guide, we’ve walked through setting up a simple deployment flow using Google Kubernetes Engine (GKE).</p><p>We’ve covered the initial setup, including cluster creation and context configuration, and the creation of a namespace and service account. We then set up an artifact repository, built and pushed a Docker image, and finally created and applied a deployment YAML file.</p><p>By following these steps, you can ensure that your application is deployed efficiently and managed effectively, leveraging the power of Kubernetes and Google Cloud. For more detailed information, refer to the <a href="https://cloud.google.com/kubernetes-engine/docs">Google Cloud documentation</a>.</p><p>Happy deploying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21a123d8ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Development: Using Multiple Node.js Versions on Windows with NVM]]></title>
            <link>https://medium.com/@tokosbex/empowering-development-using-multiple-node-js-versions-on-windows-with-nvm-ea193818918c?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea193818918c</guid>
            <category><![CDATA[nvm]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 15:58:41 GMT</pubDate>
            <atom:updated>2024-04-25T15:58:41.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eooa08zb2AYnhqqBH16lYg.png" /><figcaption><a href="https://avatars.githubusercontent.com/u/49963700?s=280&amp;v=4">Source</a></figcaption></figure><p>If you’ve worked with React or any Node.js application, you’ve likely encountered disparities between Node versions and various packages. Different projects often demand different Node versions, leading to compatibility issues when revisiting older projects. It can be frustrating, but fear not, there’s a solution.</p><p>If you find yourself facing this dilemma and would rather not reinstall your current Node version and install a new one, here’s the fix.</p><p><strong>NVM (Node Version Manager)</strong></p><p>NVM, as the name implies, is a tool for managing Node versions on your device. Instead of using npm to install and uninstall Node versions for your different projects, you can use nvm, which helps you effectively manage your node versions for each project.</p><p><a href="https://github.com/nvm-sh/nvm">NVM</a> allows you to install different versions of Node, and switch between these versions depending on the project that you’re working on via the command line.</p><p>Before proceeding, I also recommend that you uninstall Node.js if you have it installed already so that you do not have any conflicts with Node.js and nvm.</p><p>Here I’m focusing on how to install it on Windows.</p><ol><li><strong>Download NVM</strong></li></ol><p>In the <a href="https://github.com/coreybutler/nvm-windows">nvm-windows</a> repository click to download now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*GE_6Dg82nT_jG8nqKk8qTA.png" /></figure><p>2. <strong>Install the .exe file of the latest release</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7co3GVVcUkqj6Op6-YXSLQ.png" /></figure><p>3. <strong>Complete the Installation</strong></p><p>Open the file that you have downloaded, and complete the installation wizard.</p><p>When done, you can confirm that nvm has been installed by running:</p><pre>nvm -v</pre><p>If nvm was installed correctly, this command will show you the nvm version installed.</p><p><strong>Usage</strong></p><p>Now that you have nvm installed, managing multiple Node versions on your Windows system becomes a breeze. You can seamlessly install, uninstall, and switch between different Node versions.</p><p>You can install node version like:</p><pre>nvm install latest</pre><p>or</p><pre>nvm install vx.x.x</pre><p>You can easily check the installed version with:</p><pre>nvm list </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*RT_XoENgYcej2scS0zNl7A.png" /></figure><p>You can select the desired version using this command:</p><pre>nvm use vx.x.x</pre><p>I hope this information has been helpful for you and will make it easier to work with different projects and Node versions.</p><p>If you’re interested in more stories and tutorials, feel free to explore my other content!</p><p>Thank you for reading and have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea193818918c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auth Token Rotation (Node js & React ) — Part 1]]></title>
            <link>https://medium.com/@tokosbex/auth-token-rotation-node-js-react-part-1-b83a87d7fb4d?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b83a87d7fb4d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-auth]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 10:55:12 GMT</pubDate>
            <atom:updated>2024-03-18T11:07:50.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>Refresh Auth Token Rotation (Node js &amp; React ) — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZHiUJySfvgQ1F4ErzL0aw.jpeg" /><figcaption>Auth Token Rotation ( Node js &amp; React js )</figcaption></figure><p>These days, security is increasingly crucial. So, we need to be clear about at least the basics of security concerns and tips &amp; tricks. Many websites out there have weak authentication, and even if your application doesn’t contain any sensitive information, such as just a mail address, you need to respect your users and provide minimal security. In this article, I will demonstrate a simple JWT token-based authentication system with access and refresh tokens. We will use a Node.js backend, React for the frontend, and MongoDB. If you aren’t familiar with these technologies, please take some time to familiarize yourself with them before diving in. However, if you have some JavaScript skills and basic REST knowledge, then come along and delve into this with me. :)</p><p>Let’s start by setting up a Node.js backend. First, initialize the Node application:</p><pre>npm init</pre><p>Next, install Express:</p><pre>npm install express</pre><p>Here’s the file and folder hierarchy we’ll use in the backend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*77ntRw3Z6-hzeopxNWAPzQ.png" /><figcaption>Folder structure</figcaption></figure><p>Create the server.js file:</p><pre>const express = require(&quot;express&quot;);<br>const port = 5000;<br>const app = express();<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});</pre><p>Now, let’s add a database for our app. Install MongoDB. If you’re not familiar, here is a useful <a href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/">link.</a></p><pre>npm install mongoose</pre><p>Create the database connection file:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const db = mongoose<br>  .connect(&quot;mongodb://127.0.0.1/TokenRotation&quot;) //TokenRotation is the db name<br>  .then(() =&gt; console.log(&quot;Connected to MongoDB...&quot;))<br>  .catch((err) =&gt; console.error(&quot;Could not connect to MongoDB...&quot;, err));<br><br>module.exports = db;</pre><p>Don’t forget to add the database connection to server.js:</p><pre>const db = require(&quot;./dbconnection&quot;);</pre><p>Now, let’s install some additional packages:</p><pre>npm install jsonwebtoken<br>npm install dotenv<br>npm install bcrypt</pre><p>Now, let’s create the User model:</p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>const userSchema = new mongoose.Schema({<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 8,<br>    maxlength: 1024,<br>  },<br>  refreshtoken: [String],<br>});<br><br>userSchema.methods.generateAuthToken = function () {<br>  const accesstoken = jwt.sign(<br>    { _id: this._id },<br>    process.env.ACCESS_SECRET_KEY,<br>    {<br>      expiresIn: &quot;10s&quot;,<br>    }<br>  );<br>  const refreshtoken = jwt.sign(<br>    { _id: this._id },<br>    process.env.REFRESH_SECRET_KEY,<br>    { expiresIn: &quot;1d&quot; }<br>  );<br><br>  const tokens = { accesstoken: accesstoken, refreshtoken: refreshtoken };<br>  return tokens;<br>};<br><br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>exports.User = User;</pre><p>We define a schema for our user data in MongoDB.</p><p>Each user document will have an email, password, and an array to store refresh tokens.</p><p>We add a method to our user schema called <strong>generateAuthToken</strong>.</p><ul><li>This method creates both access and refresh tokens using the <strong>jsonwebtoken</strong> package.</li><li>Access token expires in 10 seconds and contains the user’s <strong>_id</strong>.</li><li>Refresh token expires in 1 day and also contains the user’s <strong>_id</strong>.</li></ul><p>We create a Mongoose model named <strong>User</strong> based on the user schema.</p><ul><li>This model will be used to interact with the MongoDB collection for users.</li><li>We export the <strong>User</strong> model for use in other parts of our application.</li></ul><h3><strong>AppError &amp; TryCatch</strong></h3><p>We’re enhancing our codebase with two utility functions for better error handling: <strong>AppError</strong> and <strong>tryCatch</strong>.</p><p>The <strong>AppError</strong> class is designed to encapsulate error information in a structured manner. It extends the native <strong>Error</strong> class and adds custom properties like <strong>errorCode</strong> and <strong>statusCode</strong>, allowing us to categorize errors and respond with appropriate HTTP status codes. This ensures consistency in error handling across our application.</p><pre>class AppError extends Error {<br>  constructor(errorCode, message, statusCode) {<br>    super(message);<br>    this.errorCode = errorCode;<br>    this.statusCode = statusCode;<br>  }<br>}<br><br>module.exports = AppError;</pre><p>The tryCatch function provides a convenient way to handle errors within our asynchronous controller functions. It takes a controller function as input and returns a new asynchronous function. This new function wraps the original controller function with a try-catch block. If an error occurs during the execution of the controller function, it’s caught, logged, and passed to the Express next function for centralized error handling. This abstraction simplifies error handling in our route handlers, promoting cleaner and more maintainable code.</p><pre>exports.tryCatch = (controller) =&gt; async (req, res, next) =&gt; {<br>  try {<br>    await controller(req, res);<br>  } catch (error) {<br>    console.log(error);<br>    return next(error);<br>  }<br>};</pre><p>By incorporating these utility functions into our codebase, we improve the readability of our error handling mechanism, ultimately enhancing the overall reliability and user experience of our application.</p><h3><strong>Routes</strong></h3><p>Next, we’ll design the endpoints for user authentication and session management, including SignIn, SignUp, RefreshToken, and LogOut. To begin, let’s lay out the routes for these functionalities.</p><pre>const express = require(&quot;express&quot;);<br>const authController = require(&quot;./controllers&quot;);<br>const verifyJWT = require(&quot;../../middleware/verifyJWT&quot;);<br><br>const router = express.Router();<br><br>//Auth based routes<br>router.post(&quot;/signUp&quot;, authController.SignUp);<br>router.post(&quot;/signIn&quot;, authController.SignIn);<br>router.get(&quot;/refresh&quot;, authController.refreshToken);<br>router.get(&quot;/logout&quot;, authController.logOut);<br><br>module.exports = router;</pre><p>In a Node.js application, services and controllers are two essential components that help organize and structure the codebase, promoting separation of concerns and maintainability.</p><ol><li><strong>Services</strong>: Services encapsulate business logic and data manipulation operations. They are responsible for performing specific tasks or operations related to a particular domain within the application. Services abstract away the details of how tasks are implemented, allowing controllers to remain lean and focused on handling HTTP requests and responses. Services are often reusable across multiple parts of the application and facilitate testing by isolating business logic from external dependencies.</li><li><strong>Controllers</strong>: Controllers handle incoming HTTP requests and define the application’s endpoints. They extract data from incoming requests, interact with services to perform necessary operations, and send back appropriate responses to clients. Controllers serve as the bridge between the client-side interface (such as a web browser or mobile app) and the underlying application logic. They organize and delegate tasks to services, ensuring that business logic remains decoupled from the presentation layer. Controllers are typically responsible for routing and request/response handling, making them a crucial component of the application’s request-response cycle.</li></ol><p>Let’s start by implementing the SignUp functionality:</p><pre>const bcrypt = require(&quot;bcrypt&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);<br>const { tryCatch } = require(&quot;../../utils/tryCatch&quot;);<br>const AppError = require(&quot;../../utils/AppError&quot;);<br>const authServices = require(&quot;./services&quot;);<br>const { User } = require(&quot;../../Models/user&quot;);<br><br>exports.SignUp = tryCatch(async (req, res) =&gt; {<br>  const { email, password } = req.body;<br>  const user = await User.find({ email: email });<br>  <br>  if (!user) {<br>    throw new AppError(<br>      409,<br>      &quot;Email address already exits in the database!&quot;,<br>      409<br>    );<br>  }<br><br>  try {<br>    const response = await authServices.signUp(email, password);<br>    const accessToken = response.token.accesstoken;<br>    const refreshToken = response.token.refreshtoken;<br>    res.cookie(&quot;jwt&quot;, refreshToken, {<br>      httpOnly: true,<br>      maxAge: 24 * 60 * 60 * 1000,<br>    });<br>    res.status(200).json({ accessToken: accessToken }).end();<br>  } catch (err) {<br>    console.log(err);<br>    res.status(err.statusCode).json(err.message).end();<br>  }<br>});</pre><p>This code snippet defines a controller function SignUp, responsible for handling user registration requests in a Node.js application. It imports necessary modules such as bcrypt for password hashing and jsonwebtoken for token generation, along with custom error handling utilities. Upon receiving a request, it extracts the email and password from the request body and checks for existing users with the same email. If no duplicate email is found, it calls a SignUp service to handle user creation, generates access and refresh tokens, sets the refresh token in an HTTP-only cookie for security, and sends the access token in the response. Any errors that occur during the SignUp process are caught and handled appropriately with error status codes and messages.</p><p>The SignUp service:</p><pre>const bcrypt = require(&quot;bcrypt&quot;);<br>const { User } = require(&quot;../../Models/user&quot;);<br>const { UserProfile } = require(&quot;../../Models/userProfile&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const ObjectId = mongoose.Types.ObjectId;<br><br>const signUp = async (email, password) =&gt; {<br>  const newUser = new User({<br>    email: email,<br>    password: password,<br>    refreshtoken: &quot;&quot;,<br>  });<br><br>  const salt = await bcrypt.genSalt(10);<br>  newUser.password = await bcrypt.hash(newUser.password, salt);<br><br>  const tokens = newUser.generateAuthToken();<br>  newUser.refreshtoken = tokens.refreshtoken;<br>  await newUser.save();<br>  const data = {<br>    token: tokens,<br>    id: newUser.id,<br>  };<br><br>  return data;<br>};</pre><p>This service function <strong>signUp</strong> is responsible for creating a new user in the application. It takes an email and password as parameters. Inside the function, a new <strong>User</strong> object is created with the provided email and password, and an empty refresh token field. The password is then hashed using bcrypt for security. After generating authentication tokens using the <strong>generateAuthToken</strong> method of the <strong>User</strong> model, which is responsible for creating access and refresh tokens, the refresh token is assigned to the user object. Finally, the new user is saved to the database, and an object containing the generated tokens and the user&#39;s ID is returned. This function ensures that user passwords are securely hashed before being stored in the database and provides authentication tokens for the newly created user.</p><p>With the same schema, we’ll now implement the SignIn functionality:</p><pre>exports.SignIn = tryCatch(async (req, res) =&gt; {<br>  const cookies = req.cookies;<br>  const { email, password } = req.body;<br>  const user = await User.findOne({ email: email });<br><br>  if (!user) {<br>    throw new AppError(<br>      404,<br>      &quot;Email address not found. Please check your email and try again.&quot;,<br>      404<br>    );<br>  }<br><br>  const validPassword = await bcrypt.compare(password, user.password);<br><br>  if (!validPassword) {<br>    throw new AppError(<br>      401,<br>      &quot;Incorrect password. Please double-check your password and try again.&quot;,<br>      401<br>    );<br>  }<br><br>  try {<br>    let newRefreshTokenArray = &quot;&quot;;<br><br>    // Check if user has an existing refresh token<br>    if (!cookies?.jwt) {<br>      refreshToken = user.refreshtoken;<br>    } else {<br>      refreshToken = cookies.jwt;<br>      const foundToken = await User.findOne({ refreshToken }).exec();<br>      <br>      if (!foundToken) {<br>        console.log(&quot;Attempted refresh token reuse at login!&quot;);<br>        // If the token is not found in the database, clear out the cookie<br>        res.clearCookie(&quot;jwt&quot;, { httpOnly: true });<br>        refreshToken = &quot;&quot;;<br>      }<br>    }<br>    const response = await authServices.signIn(user, newRefreshTokenArray);<br>    const accessToken = response.token.accesstoken;<br>    refreshToken = response.token.refreshtoken;<br>    const profilePic = response.profilePic;<br>    res.cookie(&quot;jwt&quot;, refreshToken, {<br>      httpOnly: true,<br>      maxAge: 24 * 60 * 60 * 1000,<br>    });<br>    return res<br>      .status(200)<br>      .cookie(&quot;jwt&quot;, refreshToken, {<br>        httpOnly: true,<br>        maxAge: 24 * 60 * 60 * 1000,<br>      })<br>      .json({ accessToken: accessToken, profilePic: profilePic })<br>      .end();<br>  } catch (err) {<br>    console.log(err);<br>    return res.status(err.statusCode).json(err.message).end();<br>  }<br>});</pre><p>This code segment implements the SignIn functionality in a Node.js application, handling user authentication securely. It first extracts the user’s credentials from the request body and retrieves the user from the database based on the provided email. If the user is not found or the password does not match, it throws custom errors indicating the corresponding issues. It then checks for an existing refresh token for the user and verifies its validity to prevent token reuse. Upon successful authentication, it calls a service function to generate new access and refresh tokens and retrieves the user’s profile picture. The new refresh token is set in an HTTP-only cookie for security, and the access token and profile picture are sent back in the response. Any errors encountered during the process are appropriately handled and returned as error responses with the corresponding status codes and messages.</p><pre>const signIn = async (user, newRefreshTokenArray) =&gt; {<br>  const token = user.generateAuthToken();<br>  user.refreshtoken = [...newRefreshTokenArray, token.refreshtoken];<br>  await user.save();<br>  const data = {<br>    token: token,<br>    userId: user.id,<br>  };<br>  return data;<br>};<br><br>module.exports = {<br>  signUp,<br>  signIn,<br>};</pre><p>This service function signIn handles the creation of authentication tokens and retrieval of user profile information upon successful user authentication. It takes the authenticated user object and an array of new refresh tokens as parameters. Then, it generates authentication tokens using the generateAuthToken method of the user object. The new refresh token is added to the user’s refreshtoken array, and the user object is saved back to the database. Finally, it constructs and returns an object containing the generated tokens and the user’s ID. This function ensures that authentication tokens are created and stored securely, and user information is retrieved and provided upon successful authentication.</p><p>Okay until here is a basic auth flow we just need the Logout functionality:</p><pre>exports.logOut = tryCatch(async (req, res) =&gt; {<br>  //on client, also delete the accessToken<br>  const cookies = req.cookies;<br>  if (!cookies?.jwt) return res.sendStatus(204);<br>  const refreshToken = cookies.jwt;<br>  //is refresh token in db?<br>  const foundUser = await User.findOne({ refreshtoken: refreshToken });<br>  <br>  if (!foundUser) {<br>    res.clearCookie(&quot;jwt&quot;, { httpOnly: true });<br>    return res.sendStatus(204);<br>  }<br><br>  //Delete refreshToken in db<br>  foundUser.refreshtoken = foundUser.refreshtoken.filter(<br>    (rt) =&gt; rt !== refreshToken<br>  );<br>  await foundUser.save();<br><br>  res.clearCookie(&quot;jwt&quot;, { httpOnly: true });<br>  res.sendStatus(204);<br>});</pre><p>This code snippet defines the <strong>logOut</strong> controller function responsible for handling user logout requests in a Node.js application. It utilizes the <strong>tryCatch</strong> utility for error handling. The function first checks if the user has a refresh token stored in a cookie. If not, it sends a status code of 204 (No Content) to indicate that no action is required. If a refresh token is found, the function queries the database to verify its existence. If the refresh token is not found in the database, it clears the refresh token cookie and sends a status code of 204. Otherwise, it removes the refresh token from the user&#39;s stored refresh tokens, saves the updated user object back to the database, clears the refresh token cookie, and sends a status code of 204 to indicate successful logout. This function ensures proper handling of user logout requests by managing refresh tokens securely and clearing associated cookies.</p><h3>The Refresh endpoint</h3><p>I’m sure you recognized the refresh token in all functionality. We are not used yet always just sending or deleting. Let’s talk a little bit about the refresh token.</p><p>A refresh token is a security token used in authentication systems to obtain new access tokens once they expire. Unlike access tokens, which have a short lifespan, refresh tokens are long-lived and typically last for days or even weeks. When an access token expires, the refresh token can be used to request a new access token without requiring the user to log in again. This enhances security by minimizing the exposure of sensitive credentials and reducing the frequency of user authentication. Refresh tokens are securely stored on the client-side, often in HTTP-only cookies, and are exchanged for new access tokens through a secure authentication flow.</p><p>So, does that clarify things a bit? For enhance this we need a refresh token endpoint what we can call “silent” when the user access key is expired.</p><pre>exports.refreshToken = tryCatch(async (req, res) =&gt; {<br>  const cookies = req.cookies;<br>  if (!cookies?.jwt) return res.sendStatus(401);<br>  const refreshToken = cookies.jwt;<br>  res.clearCookie(&quot;jwt&quot;, { httpOnly: true });<br>  const foundUser = await User.findOne({ refreshtoken: refreshToken });<br> <br>  if (!foundUser) {<br>    jwt.verify(<br>      refreshToken,<br>      process.env.REFRESH_SECRET_KEY,<br>      async (err, decoded) =&gt; {<br>        if (err) return res.sendStatus(403); //Forbidden<br>        const hackedUser = await User.findOne({ username: decoded._id });<br>        hackedUser.refreshtoken = [];<br>        const result = await hackedUser.save();<br>      }<br>    );<br>    return res.sendStatus(403);<br>  }<br><br>  const newRefreshTokenArray = foundUser.refreshtoken.filter(<br>    (rt) =&gt; rt !== refreshToken<br>  );<br><br>  //evaluate jwt<br>  jwt.verify(<br>    refreshToken,<br>    process.env.REFRESH_SECRET_KEY,<br>    async (err, decoded) =&gt; {<br>      if (err) {<br>        foundUser.refreshtoken = [...newRefreshTokenArray];<br>        const result = await foundUser.save();<br>      }<br>      if (err || foundUser._id.toString() !== decoded._id) {<br>        return res.sendStatus(403);<br>      }<br>      //refreshtoken still valid<br>      const accessToken = jwt.sign(<br>        { _id: decoded._id },<br>        process.env.ACCESS_SECRET_KEY,<br>        { expiresIn: &quot;10s&quot; }<br>      );<br><br>      const newRefreshToken = jwt.sign(<br>        { _id: foundUser._id },<br>        process.env.REFRESH_SECRET_KEY,<br>        { expiresIn: &quot;1d&quot; }<br>      );<br>      foundUser.refreshtoken = [...newRefreshTokenArray, newRefreshToken];<br>      const result = await foundUser.save();<br>      res.cookie(&quot;jwt&quot;, newRefreshToken, {<br>        httpOnly: true,<br>        maxAge: 24 * 60 * 60 * 1000,<br>      });<br>      res.status(200).json(accessToken);<br>    }<br>  );<br>});</pre><ol><li><strong>Checking for Refresh Token</strong>: We start by checking if there’s a refresh token stored in a cookie named “jwt.” If not, we respond with a status code of 401 (Unauthorized), indicating that the user needs to authenticate.</li><li><strong>Clearing Cookie</strong>: Regardless of whether a refresh token is found, we clear the “jwt” cookie to ensure security.</li><li><strong>Finding User</strong>: We then search for the user associated with the refresh token in our database. If the user isn’t found, we proceed to verify the refresh token’s integrity.</li><li><strong>Verifying Refresh Token</strong>: Using a secret key stored in our environment variables, we verify the refresh token. If it’s invalid or expired, we respond with a status code of 403 (Forbidden). Additionally, we locate the user whose token was used for verification and remove all refresh tokens associated with them, preventing any potential misuse.</li><li><strong>Refreshing Tokens</strong>: Assuming the refresh token is valid and associated with a user, we proceed to refresh the access and refresh tokens. We generate a new access token with a short expiration time (here, 10 second) and a new refresh token with a longer expiration time (here, 1 day). We update the user’s refresh token array with the new refresh token and save the changes to the database.</li><li><strong>Setting New Cookie</strong>: Finally, we set the new refresh token as a cookie, ensuring it’s sent securely with HTTP-only flag and a maximum age of 24 hours. We respond with a status code of 200 (OK) along with the new access token.</li></ol><p>We also need a secure endpoint in this case we get the user email from the database:</p><pre>exports.getUserData = tryCatch(async (req, res) =&gt; {<br>  const userId = req.params.id;<br>  const foundUser = await User.findOne({ _id: userId });<br><br>  const data = {<br>    userEmail: foundUser.email,<br>  };<br><br>  res.status(200).json(data).end();<br>});</pre><p>We also need to add to our routes:</p><pre>const express = require(&quot;express&quot;);<br>const authController = require(&quot;./controllers&quot;);<br>const verifyJWT = require(&quot;../../middleware/verifyJWT&quot;);<br><br>const router = express.Router();<br><br>//Auth based routes<br>router.post(&quot;/signUp&quot;, authController.SignUp);<br>router.post(&quot;/signIn&quot;, authController.SignIn);<br>router.get(&quot;/refresh&quot;, authController.refreshToken);<br>router.get(&quot;/logout&quot;, authController.logOut);<br><br>router.get(&quot;/getUser/:id&quot;, verifyJWT, authController.getUserData);<br><br>module.exports = router;</pre><p>Here I need to talk about the verifyJWT middleware:</p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>const verifyJWT = (req, res, next) =&gt; {<br>  const authHeader = req.headers[&quot;authorization&quot;];<br>  if (!authHeader) return res.sendStatus(401);<br>  console.log(authHeader);<br>  const token = authHeader.split(&quot;Bearer &quot;)[1];<br>  console.log(token);<br>  console.log(&quot;access secret&quot;, process.env.ACCESS_SECRET_KEY);<br>  jwt.verify(token, process.env.ACCESS_SECRET_KEY, (err, decoded) =&gt; {<br>    console.log(decoded);<br>    if (err) {<br>      console.log(err);<br>      return res.status(403).json({ error: &quot;Forbidden: JWT token expired!&quot; });<br>    }<br>    req.user = decoded.username;<br>    next();<br>  });<br>};<br><br>module.exports = verifyJWT;</pre><p>In this code, we’re defining a middleware function named verifyJWT, responsible for verifying JSON Web Tokens (JWT) used for authentication in our application. First, we import the jsonwebtoken package to handle JWT verification and the dotenv package to access environment variables securely. The verifyJWT function takes three parameters: req (request), res (response), and next, allowing it to operate as middleware in Express applications. Within the function, we extract the JWT token from the Authorization header of the incoming request. If the header is missing or malformed, we immediately respond with a status code of 401 (Unauthorized). Otherwise, we split the header to isolate the token from the “Bearer “ prefix. We then use jwt.verify to decode and verify the token against the access secret key stored in the environment variables. If the verification fails (e.g., due to token expiration or invalid signature), we respond with a status code of 403 (Forbidden) and an error message. Otherwise, if the token is valid, we extract the decoded payload (which typically contains user information) and attach it to the request object as req.user. Finally, we call the next function to pass control to the next middleware or route handler in the request-response cycle. This middleware ensures that only requests with valid JWT tokens are allowed to access protected routes, enhancing the security of our application.</p><p>After we created all things we need some aditional setup in our server.js for cors and cookie parsing:</p><pre>const express = require(&quot;express&quot;);<br>const cors = require(&quot;cors&quot;);<br>const db = require(&quot;./dbconnection&quot;);<br>const port = 5000;<br>const bodyParser = require(&quot;body-parser&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;);<br>const app = express();<br><br>const userRoutes = require(&quot;./apis/users/routes&quot;);<br><br>const frontendURI = &quot;http://localhost:5173&quot;;<br><br>app.use(bodyParser.json({ limit: &quot;5mb&quot; }));<br>app.use(cookieParser());<br>app.use(<br>  cors({<br>    origin: frontendURI, // Replace with your frontend domain<br>    credentials: true, // Allow credentials (cookies, authorization headers)<br>  })<br>);<br>app.use(&quot;/users&quot;, userRoutes);<br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});</pre><ol><li><strong>cors (Cross-Origin Resource Sharing)</strong>:</li></ol><ul><li>Cors middleware is responsible for enabling Cross-Origin Resource Sharing in our application. It allows resources on our server to be requested from another domain (origin) than the one it originated from. This is crucial for client-side web applications that make requests to servers on different domains.</li><li>In our code, we’re configuring cors with specific options:</li><li><strong>origin</strong>: Specifies the allowed origin or origins of cross-origin requests. In this case, we&#39;re allowing requests from a specific frontend URI (<strong>frontendURI</strong>) which is &quot;<a href="http://localhost:5173/">http://localhost:5173</a>&quot;.</li><li><strong>credentials</strong>: Indicates whether or not the server should include credentials such as cookies or authorization headers in cross-origin requests. Setting it to <strong>true</strong> allows the client to include such credentials.</li></ul><p><strong>2. bodyParser</strong>:</p><ul><li>The bodyParser middleware parses incoming request bodies and makes the parsed data available under the <strong>req.body</strong> property. It&#39;s essential for processing data sent from clients, especially when dealing with POST or PUT requests.</li><li>In our code, we’re using bodyParser.json() to parse JSON-encoded request bodies. We’re also setting a limit of 5MB for the request body size to prevent potential denial-of-service attacks by limiting the amount of data that can be sent in a single request.</li></ul><p><strong>3. cookieParser</strong>:</p><ul><li>CookieParser middleware parses cookies attached to the client’s request and makes them available under the <strong>req.cookies</strong> property. It&#39;s essential for handling cookies sent by the client, which are often used for session management, authentication, and other purposes.</li><li>In our code, we’re simply using the default settings of cookieParser without any additional configuration.</li></ul><p>Now that we’ve covered the backend implementation, it’s time to tie it all together by creating a minimal frontend for our application. By building a frontend interface, we’ll be able to interact with the backend functionalities we’ve just developed. Let’s start by setting up a basic frontend structure using React. We’ll create user interface components to interact with the authentication endpoints we’ve implemented on the backend, such as SignUp, SignIn, RefreshToken, and LogOut. Additionally, we’ll utilize tools like Axios to make HTTP requests to our backend API and handle user authentication flows seamlessly. So let’s roll up our sleeves and dive into the frontend development process to complement our backend architecture!</p><p>If you want to verify and ensure that everything is done correctly, please visit my <a href="https://github.com/tokosbence/jwt_token_rotation">GitHub repository for this code</a>.</p><p>Looking forward to seeing you <a href="https://medium.com/@tokosbex/auth-token-rotation-node-js-react-part-2-00e7a1c3a03d">in part 2</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83a87d7fb4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auth Token Rotation (Node js & React ) — Part 2]]></title>
            <link>https://medium.com/@tokosbex/auth-token-rotation-node-js-react-part-2-00e7a1c3a03d?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/00e7a1c3a03d</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[jwt-auth]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 10:54:07 GMT</pubDate>
            <atom:updated>2024-03-18T11:02:54.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>Refresh Auth Token Rotation (Node js &amp; React ) — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZHiUJySfvgQ1F4ErzL0aw.jpeg" /><figcaption>Auth Token Rotation ( Node js &amp; React js )</figcaption></figure><p>Welcome back! In this section, we’ll create a small frontend demo to test the token rotation solution we implemented in the <a href="https://medium.com/@tokosbex/auth-token-rotation-node-js-react-part-1-b83a87d7fb4d">previous part</a>. Let’s start by creating a new React app.</p><p>We create a React app with vite:</p><pre>npm create vite@latest frontend react</pre><p>And install the axios:</p><pre>npm install axios</pre><p>We’ll also install React Redux because it makes token handling much easier:</p><pre>npm install react-redux<br>npm install @reduxjs/toolkit<br>npm install react-router-dom<br>npm install redux-persist<br>npm install jwt-decode@3.1.2</pre><p><strong>Introduction to Redux Store:</strong></p><p>Redux is a state management library commonly used with React applications to manage application state in a predictable and centralized manner. The Redux store serves as a single source of truth for the entire application state, allowing components to access and update state consistently across the application. It helps simplify complex data flow and makes it easier to manage application state, especially in large-scale applications with many components.</p><p>Let’s implement the redux store what we will use in our little demo. Make a folder store and create two files: authSlice and store.</p><p>Here is the authSlice:</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br>import jwt_decode from &quot;jwt-decode&quot;;<br><br>const initialState = {<br>  token: null,<br>  userId: null,<br>};<br><br>const authTokenSlice = createSlice({<br>  name: &quot;authToken&quot;,<br>  initialState,<br>  reducers: {<br>    addToken(state, action) {<br>      const token = action.payload;<br>      const decode = jwt_decode(token);<br>      console.log(decode);<br>      const id = decode._id;<br>      console.log(&quot;ID&quot;, id);<br>      state.token = token;<br>      state.userId = id;<br>    },<br>    deleteToken(state, action) {<br>      state.token = null;<br>      state.userId = null;<br>    },<br>  },<br>});<br><br>export const authTokenActions = authTokenSlice.actions;<br><br>export default authTokenSlice;</pre><p>In this code snippet, we’re defining a Redux slice named authTokenSlice using createSlice from the Redux Toolkit. This slice manages the authentication-related state in our Redux store. The initial state includes properties for the authentication token (token), user ID (userId). The slice contains reducer functions to add or delete the authentication token from the state. When adding a token, jwt_decode is used to extract the user ID from the JWT token payload, which is then stored in the state. This slice provides actions like addToken and deleteToken, which can be dispatched to update the authentication state in the Redux store.</p><p>And here is the store:</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import authTokenSlice from &quot;./authSlice&quot;;<br>//Persist states import<br>import storageSession from &quot;redux-persist/lib/storage/session&quot;;<br>import { persistStore, persistReducer } from &quot;redux-persist&quot;;<br><br>const authTokenPersistConfig = {<br>  key: &quot;authToken&quot;,<br>  storage: storageSession,<br>};<br><br><br><br>export const store = configureStore({<br>  reducer: {<br>    authToken: persistReducer(authTokenPersistConfig, authTokenSlice.reducer),<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware({<br>      serializableCheck: false,<br>    }),<br>});<br><br>export const persistor = persistStore(store);</pre><p>In this code snippet, we’re configuring the Redux store using configureStore from the Redux Toolkit. We’re also setting up state persistence using redux-persist to persist the authToken slice’s state across browser sessions. The authTokenPersistConfig defines the configuration for persisting the authentication token slice using sessionStorage. This ensures that the authentication state persists even after the user closes and reopens the browser. Finally, we export the configured Redux store and persistor for use throughout our application. This setup provides a robust and reliable mechanism for managing authentication state in our React application.</p><p>Now we need to use it so let’s add to our main.jsx:</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.jsx&#39;<br>import &#39;./index.css&#39;<br>import { BrowserRouter } from &quot;react-router-dom&quot;;<br>import { store, persistor } from &quot;./store/store&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import { PersistGate } from &quot;redux-persist/integration/react&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  <br>    &lt;Provider store={store}&gt;<br>     &lt;PersistGate loading={null} persistor={persistor}&gt;<br>      &lt;BrowserRouter&gt;<br>       &lt;App /&gt;<br>      &lt;/BrowserRouter&gt;<br>     &lt;/PersistGate&gt;<br>    &lt;/Provider&gt;<br>  <br>)</pre><p>In this code snippet, we’re setting up the entry point for our React application. First, we import necessary dependencies such as React, ReactDOM, App component, and stylesheets. We also import BrowserRouter from “react-router-dom” to enable client-side routing in our application. Next, we import our Redux store and persistor from “./store/store” to provide centralized state management across the application. We then import Provider from “react-redux” to wrap our entire application with the Redux store, allowing components to access the Redux state. Additionally, we import PersistGate from “redux-persist/integration/react” to ensure that our Redux store is rehydrated with persisted state before rendering the application. Finally, we use ReactDOM.createRoot to render our application into the root element in the HTML document. Within the render method, we wrap our entire application with Provider and PersistGate, ensuring that the Redux store and persisted state are available throughout the component tree. Inside the Provider, we nest BrowserRouter to enable routing within our application, with the App component serving as the root component. Overall, this setup ensures seamless integration of Redux state management and client-side routing in our React application, providing a smooth and responsive user experience.</p><p>Alright, now that we’ve configured the Redux store and routing, it’s time to create our pages. We’ll start by setting up a <strong>Pages</strong> folder where we&#39;ll implement our pages. Given that this tutorial focuses on token rotation, we&#39;ll create just three pages: a main protected page, a login page, and a sign-up page.</p><p>First we implement the login page:</p><pre>import React, { useState } from &quot;react&quot;;<br>import AxiosInstance from &quot;../axios/axiosInstance&quot;;<br>import { useDispatch } from &quot;react-redux&quot;;<br>import { authTokenActions } from &quot;../store/authSlice&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>const Login = () =&gt; {<br>  const [loginData, setLoginData] = useState({<br>    email: &quot;&quot;,<br>    password: &quot;&quot;,<br>  });<br>  const [errors, setErrors] = useState({});<br>  const dispatch = useDispatch();<br>  const navigate = useNavigate();<br>  const axiosInstance = AxiosInstance({<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  });<br><br>  const onInputChangeHandle = (event) =&gt; {<br>    const { name, value } = event.target;<br>    setLoginData({ ...loginData, [name]: value });<br>    if (name === &quot;email&quot;) {<br>      errors.email = &quot;&quot;;<br>    }<br>    if (name === &quot;password&quot;) {<br>      errors.password = &quot;&quot;;<br>    }<br>  };<br><br>  const onLogin = async (e) =&gt; {<br>    e.preventDefault();<br>    const validationErrors = validateForm(loginData);<br>    if (Object.keys(validationErrors).length === 0) {<br>      console.log(loginData);<br>      await axiosInstance<br>        .post(&quot;/users/signIn&quot;, loginData)<br>        .then((response) =&gt; {<br>          if (response.data.accessToken) {<br>            dispatch(authTokenActions.addToken(response.data.accessToken));<br>            navigate(&quot;/&quot;);<br>          }<br>        })<br>        .catch((error) =&gt; {<br>          console.log(error);<br>        });<br>    } else {<br>      setErrors(validationErrors);<br>    }<br>  };<br><br>  const validateForm = (data) =&gt; {<br>    const errors = {};<br>    if (!data.password) {<br>      errors.password = &quot;Password is required&quot;;<br>    }<br>    if (!data.email) {<br>      errors.email = &quot;Email is required&quot;;<br>    } else if (!isValidEmail(data.email)) {<br>      errors.email = &quot;Invalid email format&quot;;<br>    }<br>    return errors;<br>  };<br><br>  const isValidEmail = (email) =&gt; {<br>    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;<br><br>    // Test the email against the pattern<br>    return emailPattern.test(email);<br>  };<br><br>  return (<br>    &lt;React.Fragment&gt;<br>      &lt;form style={{padding:&quot;16px&quot;, display:&quot;flex&quot;, flexDirection: &quot;column&quot;}}&gt;<br>        &lt;div&gt;<br>          &lt;h1&gt;Welcome!&lt;/h1&gt;<br>        &lt;/div&gt;<br><br>        &lt;label &gt;<br>          &lt;input<br>            <br>            name=&quot;email&quot;<br>            type=&quot;text&quot;<br>            placeholder=&quot;Email Address&quot;<br>            onChange={onInputChangeHandle}<br>          /&gt;<br>          {errors.email &amp;&amp; &lt;div &gt;{errors.email}&lt;/div&gt;}<br>        &lt;/label&gt;<br>        &lt;label &gt;<br>          &lt;input<br>            <br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            placeholder=&quot;Password&quot;<br>            onChange={onInputChangeHandle}<br>            required<br>          /&gt;<br>          {errors.password &amp;&amp; (<br>            &lt;div className={styles.error}&gt;{errors.password}&lt;/div&gt;<br>          )}<br>        &lt;/label&gt;<br><br>        &lt;div style={{padding: &quot;16px&quot;}}&gt;<br>            <br>          &lt;button<br>            <br>            <br>            onClick={onLogin}<br>            color=&quot;#faaf90&quot;<br>          &gt;Sign in&lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/form&gt;<br>    &lt;/React.Fragment&gt;<br>  );<br>};<br><br>export default Login;</pre><p>This React component, named Login, is your gateway to accessing our application. Picture it as a welcoming doorman, ready to assist you in entering our digital realm. As you enter your credentials, the component dynamically updates its state to reflect your input, ensuring a smooth and responsive experience. Once you hit that “Sign in” button, your information is securely sent to our backend server for authentication.</p><p>It utilizes React hooks such as useState to manage component state and useDispatch to dispatch actions to the Redux store. Upon user input, the onInputChangeHandle function updates the state with the entered email and password, while also performing basic form validation to ensure both fields are filled correctly. When the user submits the form, the onLogin function is triggered, which further validates the form data and sends a POST request to the backend API endpoint “/users/signIn” using Axios. If the authentication is successful, the response data containing an access token is stored in the Redux store using dispatch. Additionally, the user is redirected to the home page (“/”) using the useNavigate hook from React Router.</p><p>Now let’s see the sign up page:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>import AxiosInstance from &quot;../axios/axiosInstance&quot;;<br>import { useDispatch } from &quot;react-redux&quot;;<br>import { authTokenActions } from &quot;../store/authSlice&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>const SignUp = () =&gt; {<br>  const [formData, setFormData] = useState({<br>    //name: &quot;&quot;,<br>    email: &quot;&quot;,<br>    password: &quot;&quot;,<br>    confirmPassword: &quot;&quot;,<br>  });<br>  const [errors, setErrors] = useState({});<br>  const dispatch = useDispatch();<br>  const navigate = useNavigate();<br>  const axiosInstance = AxiosInstance({<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  });<br><br>  const onInputChangeHandle = (event) =&gt; {<br>    const { name, value } = event.target;<br>    setFormData({ ...formData, [name]: value });<br>    /*if (name === &quot;name&quot;) {<br>      errors.name = &quot;&quot;;<br>    }*/<br>    if (name === &quot;email&quot;) {<br>      errors.email = &quot;&quot;;<br>    }<br>    if (name === &quot;password&quot;) {<br>      errors.password = &quot;&quot;;<br>    }<br>    if (name === &quot;confirmPassword&quot;) {<br>      errors.passwordConfirm = &quot;&quot;;<br>    }<br>  };<br><br>  const onAuth = async (e) =&gt; {<br>    e.preventDefault();<br>    const validationErrors = validateForm(formData);<br>    if (Object.keys(validationErrors).length === 0) {<br>      console.log(formData);<br>      await axiosInstance<br>        .post(&quot;/users/signUp&quot;, formData)<br>        .then((response) =&gt; {<br>          if (response.data.accessToken) {<br>            dispatch(authTokenActions.addToken(response.data.accessToken));<br>            navigate(&quot;/&quot;);<br>          }<br>        })<br>        .catch((error) =&gt; {<br>          console.log(error);<br>        });<br>    } else {<br>      setErrors(validationErrors);<br>    }<br>  };<br><br>  const validateForm = (data) =&gt; {<br>    const passwordPattern = /^(?=.*[A-Z])(?=.*\d).+/;<br>    const errors = {};<br>    <br>    if (!data.password &amp;&amp; !data.confirmPassword) {<br>      errors.password = &quot;Password is required&quot;;<br>    } else {<br>      if (data.password.trim().length &lt; 8) {<br>        errors.password = &quot;Password is too short&quot;;<br>      }<br>      if (!passwordPattern.test(data.password)) {<br>        errors.password = &quot;Password not contains number or uppercase&quot;;<br>      }<br>      if (data.password !== data.confirmPassword) {<br>        errors.password = &quot;The passwords are not equal&quot;;<br>      }<br>    }<br>    if (!data.email) {<br>      errors.email = &quot;Email is required&quot;;<br>    } else if (!isValidEmail(data.email)) {<br>      errors.email = &quot;Invalid email format&quot;;<br>    }<br>    return errors;<br>  };<br><br>  const isValidEmail = (email) =&gt; {<br>    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;<br><br>    // Test the email against the pattern<br>    return emailPattern.test(email);<br>  };<br><br>  return (<br>    &lt;React.Fragment&gt;<br>      &lt;form style={{padding: &quot;16px&quot;, display: &quot;flex&quot;, flexDirection:&quot;column&quot;}}&gt;<br>        &lt;div &gt;<br>          &lt;h1&gt;Create your account!&lt;/h1&gt;<br>        &lt;/div&gt;<br><br>       <br><br>        &lt;label &gt;<br>          &lt;input<br>            <br>            type=&quot;text&quot;<br>            placeholder=&quot;Email&quot;<br>            name=&quot;email&quot;<br>            onChange={onInputChangeHandle}<br>          /&gt;<br>          {errors.email &amp;&amp; &lt;div &gt;{errors.email}&lt;/div&gt;}<br>        &lt;/label&gt;<br><br>        &lt;label &gt;<br>          &lt;input<br>            <br>            type=&quot;password&quot;<br>            placeholder=&quot;Password&quot;<br>            name=&quot;password&quot;<br>            onChange={onInputChangeHandle}<br>          /&gt;<br>          {errors.password &amp;&amp; (<br>            &lt;div &gt;{errors.password}&lt;/div&gt;<br>          )}<br>        &lt;/label&gt;<br><br>        &lt;label &gt;<br>          &lt;input<br>            <br>            type=&quot;password&quot;<br>            placeholder=&quot;Confirm password&quot;<br>            name=&quot;confirmPassword&quot;<br>            onChange={onInputChangeHandle}<br>          /&gt;<br>        &lt;/label&gt;<br><br>        &lt;div style={{padding: &quot;16px&quot;}}&gt;<br>            <br>          &lt;button<br>            <br>            title=&quot;Sign Up&quot;<br>            onClick={onAuth}<br>            color=&quot;#faaf90&quot;<br>          &gt;Sign Up &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/form&gt;<br>    &lt;/React.Fragment&gt;<br>  );<br>};<br><br>export default SignUp;</pre><p>This code defines a React component called SignUp, serving as the gateway for users to create new accounts within our application. It harnesses the power of React hooks, such as useState, to manage component state, and useDispatch to dispatch actions to our Redux store. As users input their desired email and password, the onInputChangeHandle function dynamically updates the component’s state, while also performing essential form validation to ensure data integrity. Upon form submission, the onAuth function orchestrates the validation process, sending a POST request to the “/users/signUp” API endpoint via Axios. If the authentication is successful, the response data — including an access token — is stored in the Redux store using dispatch. Furthermore, users are gracefully navigated to the home page (“/”) using the useNavigate hook from React Router. In summary, this component seamlessly integrates account creation functionality into our application, offering users a secure and intuitive signup experience.</p><p>As mentioned earlier, we’re developing a third secure view. Before beginning the implementation of this view, it’s essential to create a private secure route component.</p><pre>import React from &quot;react&quot;;<br>import { Outlet, Navigate } from &quot;react-router-dom&quot;;<br>import { useSelector } from &quot;react-redux&quot;;<br><br>const PrivateRoute = () =&gt; {<br>  const authToken = useSelector((state) =&gt; state.authToken.token);<br>  return authToken ? &lt;Outlet /&gt; : &lt;Navigate to=&quot;/login&quot; /&gt;;<br>};<br><br>export default PrivateRoute;</pre><p>In this code, we’re defining a React component called PrivateRoute, which serves as a wrapper for routes that require authentication in our application. The component utilizes React Router’s Outlet and Navigate components for routing and useSelector hook from react-redux for accessing the Redux store.</p><p>Inside the PrivateRoute component, we extract the authToken from the Redux store using useSelector. The authToken represents the user’s authentication token, indicating whether the user is authenticated or not.</p><p>Next, we use a ternary operator to conditionally render the Outlet component if authToken exists, implying that the user is authenticated and should have access to the protected route. The Outlet component is a placeholder provided by React Router for rendering child routes within the parent route.</p><p>If authToken does not exist (i.e., the user is not authenticated), we render the Navigate component, which redirects the user to the login page (“/login”). Navigate is a component provided by React Router for declarative navigation.</p><p>Overall, this PrivateRoute component acts as a guard for protected routes in our application, ensuring that only authenticated users can access them. If an unauthenticated user tries to access a protected route, they are automatically redirected to the login page. This enhances the security and user experience of our application by enforcing authentication requirements for sensitive routes.</p><p>Now, we can create the main page:</p><pre>import React, { useState } from &quot;react&quot;;<br>import { useDispatch, useSelector } from &quot;react-redux&quot;;<br>import { authTokenActions } from &quot;../store/authSlice&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br>import AxiosInstance from &quot;../axios/axiosInstance&quot;;<br><br>const Main = () =&gt; {<br>  const dispatch = useDispatch();<br>  const navigate = useNavigate();<br>  const userId = useSelector((state) =&gt; state.authToken.userId);<br>  const [userName, setUsername] = useState(&quot;&quot;);<br><br>  const axiosInstance = AxiosInstance({<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  });<br><br>  const onLogout = async () =&gt; {<br>    await axiosInstance<br>      .get(&quot;/users/logout&quot;)<br>      .then((response) =&gt; {<br>        console.log(response);<br>        dispatch(authTokenActions.deleteToken());<br>        navigate(&quot;/login&quot;);<br>      })<br>      .catch((error) =&gt; {<br>        console.log(error);<br>      });<br>  };<br><br>  const getUserData = async () =&gt; {<br>    await axiosInstance<br>      .get(&quot;/users/getUser/&quot; + userId)<br>      .then((response) =&gt; {<br>        console.log(response);<br>        setUsername(response.data.userEmail);<br>      })<br>      .catch((error) =&gt; {<br>        console.log(error);<br>      });<br>  };<br><br>  return (<br>    &lt;React.Fragment&gt;<br>      &lt;div&gt;Protected Main&lt;/div&gt;<br>      &lt;div style={{ display: &quot;flex&quot;, flexDirection: &quot;row&quot;, gap: &quot;10px&quot; }}&gt;<br>        &lt;button onClick={onLogout}&gt;LogOut&lt;/button&gt;<br>        &lt;button onClick={getUserData}&gt;Get User Data&lt;/button&gt;<br>      &lt;/div&gt;<br>      {userName !== &quot;&quot; &amp;&amp; &lt;div&gt;{userName}&lt;/div&gt;}<br>    &lt;/React.Fragment&gt;<br>  );<br>};<br><br>export default Main;</pre><p>In this code, we have a React component called Main, responsible for rendering the main page of our application. This component includes functionality for logging out the user and fetching user data. Let’s break down the key components:</p><ol><li><strong>useState and useSelector</strong>:</li></ol><ul><li>We use the useState hook to manage the local state of userName, representing the user’s name.</li><li>The useSelector hook is utilized to access the userId from the Redux store, retrieved using the authToken slice.</li></ul><p><strong>2. useDispatch and authTokenActions</strong>:</p><ul><li>useDispatch hook is used to get the Redux dispatch function, enabling us to dispatch actions to the Redux store.</li><li>authTokenActions contains action creators for managing authentication-related actions, such as adding or deleting authentication tokens.</li></ul><p><strong>3. useNavigate</strong>:</p><ul><li>useNavigate hook from React Router DOM is employed for declarative navigation within the application.</li></ul><p><strong>4. AxiosInstance</strong>:</p><ul><li>AxiosInstance is a configured instance of Axios, a library for making HTTP requests. It’s set up to send requests with a specific content type of “application/json”.</li></ul><p><strong>5. onLogout Function</strong>:</p><ul><li>This function is triggered when the user clicks the “LogOut” button. It sends a GET request to “/users/logout” endpoint using AxiosInstance, logging out the user on the server-side. Upon successful response, it dispatches the deleteToken action to remove the authentication token from the Redux store and navigates the user to the login page.</li></ul><p><strong>6. getUserData Function</strong>:</p><ul><li>This function fetches user data from the server by sending a GET request to “/users/getUser/{userId}” endpoint. Upon receiving a response, it sets the userName state to the retrieved user’s email. This function is invoked when the user clicks the “Get User Data” button.</li></ul><p><strong>7. Rendering</strong>:</p><ul><li>The render function displays a message indicating that the page is protected.</li><li>Two buttons are provided: one for logging out and the other for fetching user data.</li><li>If the userName state is not empty (i.e., user data has been fetched successfully), the user’s email is displayed on the page.</li></ul><p>Now, let’s add the routes to the app.jsx file:</p><pre>import &#39;./App.css&#39;<br>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import Login from &#39;./pages/Login&#39;;<br>import SignUp from &#39;./pages/SignUp&#39;;<br>import Main from &#39;./pages/MainProtected&#39;;<br>import PrivateRoute from &#39;../utils/PrivateRoute&#39;;<br><br>function App() {<br><br>  return (<br>    &lt;&gt;<br>      &lt;Routes&gt;<br>        &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>        &lt;Route path=&quot;/signUp&quot; element={&lt;SignUp/&gt;}/&gt;<br>        &lt;Route element={&lt;PrivateRoute /&gt;}&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Main/&gt;}/&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default App;</pre><p>The Routes component from react-router-dom is used to define the application’s routes. Each Route element specifies a path and the corresponding component to render. The PrivateRoute component ensures that certain routes are only accessible to authenticated users. Inside the Routes component, Login and SignUp pages are rendered directly, while the Main page is wrapped inside the PrivateRoute component to restrict access to authenticated users only. Overall, this App component sets up the application’s routing system, directing users to the appropriate pages based on the requested URLs.</p><p>Let me explain how it works!</p><p>To run the frontend, navigate to the frontend folder and:</p><pre>npm run dev</pre><p>To run the backend, navigate to the backend folder and:</p><pre>node server.js</pre><p>First you create an account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4v1DEoUMMziNVpBYTL3Gg.png" /><figcaption>Sign Up page</figcaption></figure><p>After logging in or signing up, you will be directed to the main page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eod1ctq4tYTIeFfx1XVGVg.png" /><figcaption>Main page</figcaption></figure><p>Because we’ve set the access token lifetime to 10 seconds, after this period, the access token expires. Attempting to retrieve user data results in a 403 Forbidden error due to the expired access token. This issue involves our Axios instance, as upon encountering the Forbidden error, we send a request with our refresh token from the cookies. Subsequently, we generate a new access token, pass it to the original request, and successfully retrieve the user data. If the refresh token also expires, the user will be logged out and prompted to log in again to create new refresh and access tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVhwwlW7ZOSg26GlZoUgmw.png" /><figcaption>Arhitecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtXh7iNYf1Lv0y_fnz5Hnw.png" /><figcaption>Main page after get new access token</figcaption></figure><p>This process may seem complex initially, but it’s simpler than you might expect. Remember, you can adjust the access token lifetime, but it should always be shorter than the refresh token’s lifetime.</p><p>I hope you found this tutorial enjoyable and informative. If you want to verify and ensure that everything is done correctly, please visit my <a href="https://github.com/tokosbence/jwt_token_rotation">GitHub repository for this code</a>. Don’t forget to check out my other stories!</p><p>See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00e7a1c3a03d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Establishing GKE-Datadog Connectivity: A Practical Approach to Log Monitoring Setup]]></title>
            <link>https://medium.com/@tokosbex/establishing-gke-datadog-connectivity-a-practical-approach-to-log-monitoring-setup-65231d1251af?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/65231d1251af</guid>
            <category><![CDATA[datadog-agent]]></category>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gke-autopilot]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 12:59:30 GMT</pubDate>
            <atom:updated>2024-02-28T12:59:30.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVdKPGgehFVXXTCre2g_lA.png" /></figure><p><strong>Datadog</strong> is a robust monitoring and analytics platform that collects data from various sources, including servers, databases, cloud services, and applications. It provides customizable dashboards for visualizing performance metrics, logs, and other relevant information. Datadog also offers features like alerts, synthetic monitoring, security monitoring, and network monitoring to ensure the reliability and security of your systems.</p><p>In recent updates, Datadog is introducing an advanced AI monitoring system for automated bug detection and error analysis. This system will seamlessly integrate with various platforms, including Google Cloud Engine and databases. However, our focus here is on its integration with Google Kubernetes Engine (GKE).</p><p>Initially, connecting Datadog with Kubernetes, specifically GKE, seemed daunting due to limited information available. To assist others facing similar challenges, I’ll share my insights.</p><p>Before we dive into the integration process, let’s briefly discuss Helm and Helm Charts. Helm is a package manager tailored for Kubernetes, simplifying the management of Kubernetes applications. Helm Charts enable easy installation, creation, versioning, and sharing of Kubernetes applications, much like NPM for Node.js or pip for Python.</p><p><strong>Now, let’s begin!</strong></p><p>Start by creating a Datadog account and locating your API key. You can find it on the initial page or under Organization settings, in the “API keys” or “Client Tokens” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgRNObuqtk4gFjQnf3XjsA.png" /></figure><p>After obtaining the API Key, you’ll need to generate an App Key. You can find or create a new App Key in the same location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yz7usPDliqQW46KxY6tOZQ.png" /></figure><p>Armed with these two pieces of information, we can proceed to the Google SDK and begin integrating our Datadog service with our GKE instance.</p><p>To prioritize security, we’ll store the API key and App key in secret variables.</p><pre>kubectl create secret generic datadog-secret --from-literal api-key=&lt;DATADOG_API_KEY&gt; --from-literal app-key=&lt;DATADOG_APP_KEY&gt;</pre><p>Following this step, we can proceed to install Datadog using Helm:</p><pre>helm install datadog-agent \<br>    --set datadog.apiKey=&lt;DATADOG_API_KEY&gt; \<br>    --set datadog.appKey=&lt;DATADOG_APP_KEY&gt; \<br>    --set datadog.site=&lt;DATADOG_SITE&gt;\<br>    --set clusterAgent.enabled=true \<br>    --set clusterAgent.metricsProvider.enabled=true \<br>    --set providers.gke.autopilot=true \<br>    --set datadog.logs.enabled=true \<br>    --set datadog.apm.enabled=true \<br>    --set datadog.kubeStateMetricsEnabled=false \<br>    --set datadog.kubeStateMetricsCore.enabled=true \<br>    datadog/datadog</pre><p>You can input the API key and the app key in their respective fields, and you also have the option to select your preferred location site, such as <a href="http://datadog.eu/">datadog.eu</a> or <a href="http://datadog.com/">datadog.com</a>.</p><p>Great! With Datadog installed, the next step is to create our Datadog agent in GKE. Start by creating the <strong>datadog-agent.yaml</strong> file:</p><pre>apiVersion: datadoghq.com/v2alpha1<br>kind: DatadogAgent<br>metadata:<br>  name: datadog<br>spec:<br>  global:<br>    credentials:<br>      apiSecret:<br>        secretName: datadog-secret<br>        keyName: api-key<br>    site: &quot;datadoghq.eu&quot; <br>  override:<br>    nodeAgent:<br>      tolerations:<br>        - effect: NoSchedule<br>          key: cloud.google.com/gke-spot<br>          operator: Equal<br>          value: &quot;true&quot;    <br>  features:<br>    logCollection:<br>      enabled: true<br>      containerCollectAll: true</pre><p>Following the creation of the <strong>datadog-agent.yaml</strong> file, apply it on the GKE:</p><pre>kubectl apply -f datadog-agent.yaml</pre><p>And there you have it! Your Datadog agent is now operational on the GKE cluster, allowing you to effortlessly monitor your logs within the Datadog platform. From here, you have the freedom to customize your own dashboard, tailor metrics to your preferences, and enhance the value of your logging process. Should you require specific metrics, you can easily add or create service accounts within your Datadog account. <a href="https://docs.datadoghq.com/integrations/google_cloud_platform/">Explore the setup process here</a>.</p><p><strong>Happy monitoring!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65231d1251af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Your Frontend Workflow: Exploring Apollo Client for GraphQL Operations]]></title>
            <link>https://medium.com/@tokosbex/simplify-your-frontend-workflow-exploring-apollo-client-for-graphql-operations-d00ae188b427?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00ae188b427</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 12:00:18 GMT</pubDate>
            <atom:updated>2024-02-28T12:00:18.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*c6BaVu-zTuZk8zsyDOJuZw.jpeg" /></figure><p><strong>Hi there!</strong></p><p>When we typically develop a web application, we need to create both a frontend and a backend. In this architectural setup, these two components must communicate with each other, typically via an HTTP connection. Traditionally, we create separate HTTP endpoints for various functionalities such as user integration or product integration. However, this can lead to the creation of numerous endpoints, resulting in extensive code that becomes difficult to maintain. This is where Apollo Client and GraphQL come in to help by allowing us to consolidate these endpoints into a single one that the frontend consumes.</p><p>In this article, I focus on the Apollo Client aspect. If you’re interested in learning more about GraphQL and Node.js implementation, I recommend checking out my previous <a href="https://medium.com/@tokosbex/graphql-and-node-js-part-1-f54669498383"><strong>article</strong></a><strong>.</strong></p><p><strong>Apollo Client</strong></p><p>Apollo Client is a powerful GraphQL client that connects to GraphQL APIs in JavaScript applications. It enables you to query, mutate, and subscribe to data, manage application state, and cache data to optimize performance. It is built on top of popular JavaScript libraries like React, and is easy to use in various environments. Apollo Client streamlines data management, enabling you to create high-performance, responsive user experiences, whether you are building a simple prototype or a complex production application.</p><p><strong>How does it work?</strong></p><p>The client creates a GraphQL operation: When you use Apollo Client to query, mutate, or subscribe to data, you create a GraphQL operation object that defines the operation you want to perform. This object includes the operation type (query, mutation, or subscription), the query or mutation document, any variables to be passed to the server, and any other necessary metadata</p><p>Apollo Client sends the HTTP request: Once the GraphQL operation object is created, Apollo Client passes it to the HTTP transport, which sends a POST request to the GraphQL API server with the operation and any associated variables in the request body.</p><p>The GraphQL API server processes the request: The GraphQL API server receives the HTTP POST request and processes it according to the GraphQL specification. It executes the operation defined in the request and returns a response that includes the requested data and any associated errors.</p><p>Apollo Client receives the response: Once the HTTP request is complete, Apollo Client receives the response from the server and parses it into a format that can be used by your application. The response is then made available to your application code through the appropriate Apollo Client API (e.g. <strong>useQuery</strong>, <strong>useMutation</strong>, etc.)</p><p>The client updates the cache: If the response from the server includes data that is already stored in Apollo Client’s cache, the cache is updated with the new data. This allows subsequent queries to be served from the cache instead of making additional requests to the server.</p><p>So, let’s install Apollo Client:</p><pre>npm install @apollo/client graphql</pre><p>Apollo Client creates an HTTP transport: When you configure an Apollo Client instance, you provide it with an HTTP transport that knows how to send HTTP requests to your GraphQL API server. By default, Apollo Client uses the <strong>apollo-link-http</strong> package to create an HTTP transport.</p><p>First, we need to import the necessary modules from the “@apollo/client” library. These modules include:</p><ul><li>ApolloClient: A class used to create a new Apollo client that can connect to a GraphQL server.</li><li>InMemoryCache: A class used to store data in the client’s cache.</li><li>ApolloProvider: A component used to wrap the application and provide the client with all child components.</li><li>HttpLink: A class used to create an HTTP link to the GraphQL server.</li><li>from: A function used to combine multiple links into a single composite link.</li><li>onError: A function used to handle errors that occur during communication with the server.</li></ul><pre>import {<br>  ApolloClient,<br>  InMemoryCache,<br>  ApolloProvider,<br>  HttpLink,<br>  from,<br>} from &quot;@apollo/client&quot;;<br>import { onError } from &quot;@apollo/client/link/error&quot;;</pre><p>Next, we define an error-handling function using the “onError” module. This function is called whenever an error occurs during communication with the server, and it handles both GraphQL errors and network errors. If a GraphQL error occurs, the function displays an alert with the error message.</p><pre>const errorLink = onError(({ graphqlErrors, networkError }) =&gt; {<br>   if (graphqlErrors) {<br>      graphqlErrors.map(({ message, location, path }) =&gt; {<br>      alert(`Graphqlerror ${message}`);<br>   });<br> }<br>});</pre><p>After defining the error handling function, the code creates an HTTP link to the GraphQL server using the “HttpLink” module. The link is configured to connect to the server at “<a href="http://localhost:5000/graphql">http://localhost:5000/graphql</a></p><pre>const link = from([<br>    errorLink,<br>    new HttpLink({ uri: &quot;http://localhost:5000/graphql&quot; }),<br>]);</pre><p>Next, the code creates a new Apollo client using the “ApolloClient” module. The client is configured with an in-memory cache and the composite link that was created earlier.</p><pre>const client = new ApolloClient({<br>      cache: new InMemoryCache(),<br>      link: link,<br>});</pre><p>Finally, the code exports the “ApolloProvider” component, which wraps the application and provides the Apollo client to all child components.</p><pre>export default function App() {<br>  return (<br>          &lt;ApolloProvider client={client}&gt;<br>            &lt;div&gt;My App&lt;/div&gt;<br>          &lt;/ApolloProvider&gt;<br>          );<br>}</pre><p>By wrapping the application with the “ApolloProvider” component and passing in the Apollo client, the application is able to execute GraphQL queries and mutations against the server and store the results in the cache.</p><p>The code snippets above can be implemented in the main <strong>App.js</strong>. Inside every component wrapped by the <strong>ApolloProvider</strong>, you can utilize the Apollo Client.</p><p>However, our work isn’t finished yet. We still need to create the queries and mutations that we’ll use in our application. To accomplish this, we can create a separate folder within our frontend app and organize it into two files: one for queries and one for mutations.</p><p>Let’s begin with the queries. Our objective is to load all products from the GraphQL server using the following query:</p><pre>import { gql } from &quot;@apollo/client&quot;;<br><br>export const LOAD_PRODUCTS = gql`<br>  query {<br>    getAllProduct {<br>      id<br>      brand<br>      category<br>      description<br>      discountPercentage<br>      images<br>      price<br>      rating<br>      stock<br>      thumbnail<br>      title<br>    }<br>  }<br>`;</pre><p>It is requesting to load all products and specifies the fields to be fetched for each product, including id, brand, category, description, discountPercentage, images, price, rating, stock, thumbnail, and title.</p><p>Let’s load just one product:</p><pre>export const LOAD_PRODUCT = gql`<br>  query getProduct($id: String!) {<br>    getProduct(id: $id) {<br>      id<br>      brand<br>      category<br>      description<br>      discountPercentage<br>      images<br>      price<br>      rating<br>      stock<br>      thumbnail<br>      title<br>    }<br>  }<br>`;</pre><p>This query is designed to retrieve a single product based on its id. The query accepts a variable $id of type String and fetches the same set of fields for the product as in the previous query. The getProduct field is used to fetch the product data, with the id parameter being passed dynamically using GraphQL variables.</p><p>We’ve defined our queries, so now it’s time to put them to use. Thanks to our organized separation, we can access these queries from anywhere within our application. All we need to do is utilize the Apollo Client Hooks to integrate them seamlessly into our components. Apollo Client handles the request cycle from start to finish, including tracking, loading and error states. There’s no middleware or boilerplate code to set up before making your first request, and you don’t need to worry about transforming or caching responses. Apollo Client useQuery hook leverages React’s Hook API to bind a query to a component, enabling that component to render a query’s results immediately. Basically, the useQuery hook encapsulates the logic for retrieving your data, tracking, loading and error states and updating your UI.</p><p>Imagine we’re in the “product list component,” and our goal is to display a list of all products.</p><pre>import { LOAD_PRODUCTS } from &quot;../../GraphQL/Queries&quot;;<br>import { useQuery } from &quot;@apollo/client&quot;;<br><br>const { error, loading, data } = useQuery(LOAD_PRODUCTS);</pre><ol><li><strong>import { LOAD_PRODUCTS } from &quot;../../GraphQL/Queries&quot;;</strong>: This line imports the <strong>LOAD_PRODUCTS</strong> query from a file located at &quot;../../GraphQL/Queries&quot;. This file likely contains GraphQL queries defined using the <strong>gql</strong> function from Apollo Client.</li><li><strong>import { useQuery } from &quot;@apollo/client&quot;;</strong>: This line imports the <strong>useQuery</strong> hook from the <strong>@apollo/client</strong> package. This hook is used to execute GraphQL queries in React components.</li><li><strong>const { error, loading, data } = useQuery(LOAD_PRODUCTS);</strong>: This line uses the <strong>useQuery</strong> hook to execute the <strong>LOAD_PRODUCTS</strong> query. The hook returns an object with three properties:</li></ol><ul><li><strong>error</strong>: If an error occurs during the execution of the query, it will be stored in this property.</li><li><strong>loading</strong>: This property indicates whether the query is still loading or not. It will be true while the query is in progress.</li><li><strong>data</strong>: If the query is successful, the fetched data will be stored in this property.</li></ul><p><strong>How simple is that, right?</strong></p><p>If we wish to utilize the single product query, we simply pass the parameters into the query hook:</p><pre>const { error, loading, data } = useQuery(LOAD_PRODUCT, {<br>    variables: {<br>      id: id,<br>    },<br>  });</pre><p>Now that we’ve set up queries, we also require mutations to send data to the GraphQL server.</p><pre>import { gql } from &quot;@apollo/client&quot;;<br><br>export const CREATE_PRODUCT_MUTATION = gql`<br>  mutation createProduct(<br>    $brand: String!<br>    $category: String!<br>    $description: String!<br>    $discountPercentage: Float!<br>    $images: String!<br>    $price: Float!<br>    $rating: Float!<br>    $stock: Int!<br>    $thumbnail: String!<br>    $title: String<br>  ) {<br>    createProduct(<br>      brand: $brand<br>      category: $category<br>      description: $description<br>      discountPercentage: $discountPercentage<br>      images: $images<br>      price: $price<br>      rating: $rating<br>      stock: $stock<br>      thumbnail: $thumbnail<br>      title: $title<br>    ) {<br>      id<br>    }<br>  }<br>`;</pre><p>This Apollo Client mutation named CREATE_PRODUCT_MUTATION creates a new product on the server. It takes various input variables such as brand, category, description, etc., and uses them to create a product. After creation, it returns the ID of the newly created product.</p><p>And here is an updated mutation:</p><pre>export const UPDATE_PRODUCT_MUTATION = gql`<br>  mutation updateProduct(<br>    $id: String!<br>    $brand: String!<br>    $category: String!<br>    $description: String!<br>    $discountPercentage: Float!<br>    $images: String!<br>    $price: Float!<br>    $rating: Float!<br>    $stock: Int!<br>    $thumbnail: String!<br>    $title: String<br>  ) {<br>    updateProduct(<br>      id: $id<br>      brand: $brand<br>      category: $category<br>      description: $description<br>      discountPercentage: $discountPercentage<br>      images: $images<br>      price: $price<br>      rating: $rating<br>      stock: $stock<br>      thumbnail: $thumbnail<br>      title: $title<br>    ) {<br>      id<br>    }<br>  }<br>`;</pre><p>This Apollo Client mutation, named <strong>UPDATE_PRODUCT_MUTATION</strong>, updates an existing product on the server. It requires the product&#39;s ID along with various properties like brand, category, description, etc., to perform the update. After the update is executed, it returns the ID of the updated product.</p><p>And maybe you guessed we have another hook for using the mutations also. The useMutation hook.</p><p>The <strong>useMutation</strong> hook in Apollo Client is a powerful tool for performing mutations in React components. It enables developers to execute GraphQL mutation operations and handle the resulting data and loading/error states seamlessly within their components. By utilizing this hook, React components can trigger mutations, such as creating, updating, or deleting data, in response to user interactions or other events. The <strong>useMutation</strong> hook returns a function to execute the mutation and provides objects representing the loading state, any errors that occur during the mutation process, and the data returned from the server after a successful mutation. This allows developers to easily integrate mutation functionality into their React applications, providing a smooth and efficient user experience while managing complex data interactions with GraphQL servers.</p><p>Let’s say we’re creating a new product:</p><pre>import { CREATE_PRODUCT_MUTATION } from &quot;../../GraphQL/Mutations&quot;;<br>import { useMutation } from &quot;@apollo/client&quot;;<br><br>const [createProduct, { error }] = useMutation(CREATE_PRODUCT_MUTATION);<br><br>createProduct({<br>      variables: {<br>        brand: newProduct.brand,<br>        category: newProduct.category,<br>        description: newProduct.description,<br>        discountPercentage: parseFloat(newProduct.discountPersentage),<br>        images: newProduct.images,<br>        price: parseFloat(newProduct.price),<br>        rating: parseFloat(newProduct.rating),<br>        stock: parseInt(newProduct.stock),<br>        thumbnail: newProduct.thumbnail,<br>        title: newProduct.title,<br>      },<br>    });</pre><ol><li><strong>import { CREATE_PRODUCT_MUTATION } from &quot;../../GraphQL/Mutations&quot;;</strong>: This line imports the <strong>CREATE_PRODUCT_MUTATION</strong> mutation from a file located at &quot;../../GraphQL/Mutations&quot;. This file likely contains the definition of the GraphQL mutation using the <strong>gql</strong> function provided by Apollo Client.</li><li><strong>import { useMutation } from &quot;@apollo/client&quot;;</strong>: This line imports the <strong>useMutation</strong> hook from the <strong>@apollo/client</strong> package. This hook is used to execute GraphQL mutations in React components.</li><li><strong>const [createProduct, { error }] = useMutation(CREATE_PRODUCT_MUTATION);</strong>: This line utilizes the <strong>useMutation</strong> hook to execute the <strong>CREATE_PRODUCT_MUTATION</strong> mutation. It returns an array with two elements:</li></ol><ul><li><strong>createProduct</strong>: This is a function that can be called to trigger the mutation. It accepts an object containing variables required for the mutation.</li><li><strong>{ error }</strong>: This object contains any errors that occur during the execution of the mutation.</li></ul><p>4. <strong>createProduct({ variables: { ... } });</strong>: This line calls the <strong>createProduct</strong> function returned by the <strong>useMutation</strong> hook. It triggers the mutation with the provided variables. The variables object contains data for the new product, such as brand, category, description, etc. These values are likely obtained from some form input or state variables in the component.</p><p>This demonstrates the fundamental usage of the useQuery and useMutation hooks. However, you might have some questions regarding their usage. For instance, how do we fetch updated data after performing an update? Additionally, how can we include an authentication header in these queries or mutations? These are more simple than you thought :)</p><p>If we need to include headers, we simply utilize the context parameter in our queries or mutations:</p><pre>const [updateProduct, { updateError }] = useMutation(<br>    UPDATE_PRODUCT_MUTATION,<br>    {<br>      context: {<br>        headers: {<br>          Authorization: &quot;Bearer &quot; + authContext.token,<br>        },<br>      },<br>    }<br>  );</pre><p><strong>context: { headers: { Authorization: “Bearer “ + authContext.token } }</strong>: Within the second argument of the useMutation hook, the context property is used to specify additional context options for the mutation operation.</p><p>If we want to refresh the loaded data after updating a product, we simply include a refetchQueries parameter.</p><pre>updateProduct({<br>      variables: {<br>        id: id,<br>        brand: productData.brand,<br>        category: productData.category,<br>        description: productData.description,<br>        discountPercentage: parseFloat(productData.discountPercentage),<br>        images: productData.images,<br>        price: parseFloat(productData.price),<br>        rating: parseFloat(productData.rating),<br>        stock: parseInt(productData.stock),<br>        thumbnail: productData.thumbnail,<br>        title: productData.title,<br>      },<br>      refetchQueries: [LOAD_PRODUCTS],<br>    });</pre><ul><li><strong>refetchQueries: [LOAD_PRODUCTS]</strong>: This parameter specifies an array of queries that should be refetched after the mutation is completed. In this case, <strong>LOAD_PRODUCTS</strong> is the query that fetches all products. By including it in the <strong>refetchQueries</strong> array, the client ensures that after the product update is performed, the data fetched by the <strong>LOAD_PRODUCTS</strong> query will be refreshed to reflect the changes made by the mutation.</li></ul><p>In summary, the <strong>refetchQueries</strong> parameter allows you to specify which queries should be refetched after a mutation is executed, ensuring that the client&#39;s data stays up-to-date with the changes made on the server.</p><p>In conclusion, the integration of GraphQL and Apollo Client offers a straightforward and efficient approach to managing data interactions within your application. With features like hooks such as <strong>useQuery</strong> and <strong>useMutation</strong>, along with options like <strong>refetchQueries</strong>, handling data retrieval and manipulation becomes more intuitive. As evidenced by the examples provided, the process is simplified and the code remains maintainable, allowing for smoother development experiences. You see? It is not that hard and makes the code way simpler and more maintainable when utilizing GraphQL and Apollo Client.</p><p><strong>See you next time!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00ae188b427" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL and Node js — Part 1]]></title>
            <link>https://medium.com/@tokosbex/graphql-and-node-js-part-1-f54669498383?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f54669498383</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 19:24:49 GMT</pubDate>
            <atom:updated>2024-01-15T19:24:49.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL and Node js — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZTJDP3NkY0Zzag_eIEHCw.png" /><figcaption>GraphQL and Node Js</figcaption></figure><p><strong>Introduction</strong></p><p><strong>GraphQL </strong>and <strong>Node.js </strong>make a dynamic duo in modern web development. GraphQL is a query language for your API, while Node.js is a robust runtime environment for server-side applications. When combined, they empower developers to create efficient, flexible, and real-time communication between clients and servers.</p><p>The <strong>advantage of using GraphQL</strong> with Node.js lies in its ability to provide a single endpoint for clients to request precisely the data they need, minimizing over-fetching and under-fetching of information. This seamless synergy enables developers to build powerful, customizable APIs and simplifies data communication by allowing clients to specify their data requirements through queries and mutations, ensuring a more efficient and responsive backend experience.</p><p>Only one endpoint! Sounds cool, right? So why wait any longer? Let’s start developing!</p><p>First, we create the base node app with the following command:</p><pre>npm init </pre><p>After we initialized our starting app, let’s install the necessary node packages:</p><pre>npm install express</pre><p>Express module is a web application framework that simplifies the process of building web servers and APIs. It offers a wide range of features, including routing, middleware support, and a straightforward API for handling HTTP requests and responses. Express is known for its flexibility, allowing developers to create both simple single-page applications and complex, enterprise-grade projects with ease.</p><p>Let’s create our app in the index.js:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = 5000;<br><br>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>To run our app just type <strong>node index.js</strong> and our application is running on <strong>http//:localhost:5000/</strong></p><p>Now we install the other necessary libraries and along the way you would see what these packages doing.</p><p>We will work with Mongo DB so if you not have installed on your machine then follow the instructions from here:</p><p><a href="https://www.mongodb.com/docs/manual/installation/">https://www.mongodb.com/docs/manual/installation/</a> .</p><p>After you have installed on your machine then install the mongoose package with we can interact between the node js and the database.</p><pre>npm install mongoose</pre><p>MongoDB is a popular NoSQL database management system known for its flexibility and scalability. It stores data in a document-oriented format, using BSON (Binary JSON). It is widely used in web and mobile applications, offering developers the ability to work with data in a more dynamic and agile manner compared to traditional relational databases. Our first task is to create a connection between our application and the database.</p><p>Edit the <strong>index.js</strong>:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const mongoose = require(&quot;mongoose&quot;);<br>const PORT = 5000;<br><br>mongoose<br>  .connect(&quot;mongodb://127.0.0.1/{Your db collection name}&quot;)<br>  .then(() =&gt; console.log(&quot;Connected to MongoDB...&quot;))<br>  .catch((err) =&gt; console.error(&quot;Could not connect to MongoDB...&quot;));<br><br>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>So after we have the initial app and we connected to a db we can kick off our journey with GraphQL. Let’s install the necessary packages:</p><pre>npm install express-graphql graphql</pre><p><strong>Express-GraphQL</strong> is a middleware package for Node.js and <strong>Express.js </strong>that simplifies the process of creating a GraphQL API. It provides an easy way to expose a GraphQL endpoint in an Express application.</p><p><strong>Key Features</strong></p><ul><li><strong>Middleware Integration</strong>: Express-GraphQL seamlessly integrates with Express.js, making it a popular choice for adding GraphQL functionality to existing Express applications.</li><li><strong>Schema Definition</strong>: You can define your GraphQL schema using the GraphQL.js schema language, and Express-GraphQL helps in routing requests to the appropriate schema.</li><li><strong>Data Resolution</strong>: It allows you to define resolvers that specify how to fetch data from your data sources, whether it’s a database or other APIs.</li><li><strong>Query Validation</strong>: Express-GraphQL automatically validates and executes GraphQL queries and provides detailed error messages.</li></ul><p>GraphQL is a query language and runtime for APIs. It was developed by Facebook and is designed to provide a more efficient, powerful, and flexible alternative to the traditional REST API.</p><p><strong>Key Features</strong></p><ul><li><strong>Client-Defined Queries</strong>: With GraphQL, clients can request exactly the data they need, avoiding over-fetching or under-fetching of data, which is common in REST.</li><li><strong>Strongly Typed</strong>: GraphQL APIs are strongly typed. You define the types, queries, and mutations, which helps in catching errors early.</li><li><strong>Single Endpoint</strong>: GraphQL typically has a single endpoint for all requests, making it efficient and reducing the number of network requests.</li><li><strong>Real-time Data</strong>: GraphQL supports real-time data using subscriptions, enabling features like live updates and chat functionality.</li><li><strong>Introspection</strong>: You can introspect a GraphQL schema to understand its capabilities and structure.</li></ul><p>For the better project organization create a folder Schema, inside this folder, we create a folder for our model types and an index.js for the routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*vDhxmbfo1YhEM4JhZNAOeA.png" /><figcaption>Type definitions</figcaption></figure><p>As you can see here, we have 3 types and 3 models in our database. Let’s create another folder for the database models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*0juYzu71wQ41kcBusk3FXg.png" /><figcaption>Models</figcaption></figure><p>In the <strong>orders</strong>, we create our <strong>order model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const orderSchema = new mongoose.Schema({<br>  userId: {<br>    type: String,<br>    required: true,<br>  },<br>  firstName: {<br>    type: String,<br>    required: true,<br>  },<br>  lastName: {<br>    type: String,<br>    required: true,<br>  },<br>  address: {<br>    type: String,<br>    required: true,<br>  },<br>  city: {<br>    type: String,<br>    required: true,<br>  },<br>  country: {<br>    type: String,<br>    required: true,<br>  },<br>  zipCode: {<br>    type: String,<br>    required: true,<br>  },<br>  totalAmount: {<br>    type: Number,<br>    required: true,<br>  },<br>  items: {<br>    type: String,<br>    required: true,<br>  },<br>  createdDate: {<br>    type: String,<br>    required: true,<br>  },<br>});<br><br>const Order = mongoose.model(&quot;Order&quot;, orderSchema);<br><br>exports.Order = Order;</pre><p>Create the <strong>product model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const productSchema = new mongoose.Schema({<br>  title: {<br>    type: String,<br>    required: true,<br>  },<br>  description: {<br>    type: String,<br>    required: true,<br>  },<br>  price: {<br>    type: Number,<br>    required: true,<br>  },<br>  discountPercentage: {<br>    type: Number,<br>    required: true,<br>  },<br>  rating: {<br>    type: Number,<br>    required: true,<br>  },<br>  stock: {<br>    type: Number,<br>    required: true,<br>  },<br>  brand: {<br>    type: String,<br>    required: true,<br>  },<br>  category: {<br>    type: String,<br>    required: true,<br>  },<br>  thumbnail: {<br>    type: String,<br>    required: true,<br>  },<br>  images: {<br>    type: String,<br>    required: true,<br>  },<br>});<br><br>const Product = mongoose.model(&quot;Product&quot;, productSchema);<br><br>exports.Product = Product;</pre><p>And finally our <strong>user model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const userSchema = new mongoose.Schema({<br>  username: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 50,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 225,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 1024,<br>  },<br>  isAdmin: {<br>    type: Boolean,<br>    default: false,<br>  },<br>});<br><br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>exports.User = User;</pre><p>These models are MongoDB models that we’ll be using to save and retrieve information from the database. In the context of a Node.js application, MongoDB models represent the structure of the data you want to store in your database. They define the schema and behavior of the data, making it easier to interact with the MongoDB database. By defining models, you can enforce a specific structure for your data and perform operations like inserts, updates, and queries efficiently. This not only simplifies the interaction with the database but also enhances code organization and maintainability, making MongoDB models a fundamental part of your application’s data layer.</p><p>Now we have the models we can create the <strong>OrderType</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const {<br>  GraphQLObjectType,<br>  GraphQLInt,<br>  GraphQLString,<br>  GraphQLFloat,<br>  GraphQLList,<br>} = graphql;<br><br>const OrderType = new GraphQLObjectType({<br>  name: &quot;Order&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    userId: { type: GraphQLString },<br>    firstName: { type: GraphQLString },<br>    lastName: { type: GraphQLString },<br>    address: { type: GraphQLString },<br>    city: { type: GraphQLString },<br>    country: { type: GraphQLString },<br>    zipCode: { type: GraphQLString },<br>    totalAmount: { type: GraphQLFloat },<br>    items: { type: GraphQLString },<br>    createdDate: { type: GraphQLString },<br>  }),<br>});<br><br>module.exports = OrderType;</pre><p>In <strong>GraphQL</strong>, a type definition like the one you provided represents the structure of data that can be queried or manipulated. Let me explain it in simpler terms:</p><p>Imagine you have an online store, and you want to retrieve information about orders placed by customers. You’d define an <strong>“OrderType”</strong> using GraphQL to specify what kind of data you can request about an order.</p><p>Here’s a breakdown of the code you provided:</p><ol><li>You import the necessary modules from the <strong>“graphql”</strong> package.</li><li>You define the <strong>“OrderType”</strong> using the <strong>“GraphQLObjectType”</strong> constructor. This is where you describe the structure of an order.</li></ol><ul><li><strong>“name”</strong> is a label for this type, in this case, <strong>“Order”.</strong></li><li><strong>“fields”</strong> is a function that returns an object. This object describes the properties (fields) of an order, and each field is associated with a specific data type.</li></ul><p>3. Inside the <strong>“fields”</strong> object, you define various properties that an order can have:</p><ul><li><strong>“id,” “userId,” “firstName,” “lastName,”</strong> and so on are fields that describe different aspects of an order.</li><li><strong>“type”</strong> specifies the data type for each field. For example, <strong>“id”</strong> and <strong>“userId”</strong> are of type <strong>“GraphQLString,” </strong>which means they hold text data.</li><li><strong>“totalAmount”</strong> is of type <strong>“GraphQLFloat,”</strong> indicating it holds numeric data.</li><li><strong>“items” </strong>is also of type <strong>“GraphQLString,”</strong> but this might represent a serialized list of items, like a JSON string.</li></ul><p>4. Finally, you export the <strong>“OrderType”</strong> so that you can use it in your <strong>GraphQL schema</strong> to define the structure of your data.</p><p>In summary, the <strong>“OrderType”</strong> is a blueprint that defines the structure of an order in your online store’s data. When a GraphQL query is made, it specifies which fields (properties) of an order should be included in the response. This makes it very flexible for clients to request only the data they need, and the <strong>“OrderType”</strong> helps ensure that the data conforms to a specific structure.</p><p>We do the same for the <strong>product</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLFloat } = graphql;<br><br>const ProductType = new GraphQLObjectType({<br>  name: &quot;Product&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    brand: { type: GraphQLString },<br>    category: { type: GraphQLString },<br>    description: { type: GraphQLString },<br>    discountPercentage: { type: GraphQLFloat },<br>    images: { type: GraphQLString },<br>    price: { type: GraphQLFloat },<br>    rating: { type: GraphQLFloat },<br>    stock: { type: GraphQLInt },<br>    thumbnail: { type: GraphQLString },<br>    title: { type: GraphQLString },<br>  }),<br>});<br><br>module.exports = ProductType;</pre><p>And also for the <strong>users</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLFloat } = graphql;<br><br>const UserType = new GraphQLObjectType({<br>  name: &quot;User&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    username: { type: GraphQLString },<br>    email: { type: GraphQLString },<br>    password: { type: GraphQLString },<br>    isAdmin: { type: graphql.GraphQLBoolean },<br>  }),<br>});<br><br>module.exports = UserType;</pre><p>Once we have defined our GraphQL types, we can proceed to define our queries and mutations. GraphQL queries serve the purpose of retrieving data, enabling clients to request precisely the information they require. Conversely, mutations are employed to alter server data, providing a reliable and secure means of executing write operations.</p><p>Let’s write the code into<strong> index.js:</strong></p><pre>// Import necessary GraphQL modules and dependencies.<br>const graphql = require(&quot;graphql&quot;);<br>const {<br>  GraphQLSchema,<br>  GraphQLObjectType,<br>  GraphQLInt,<br>  GraphQLString,<br>  GraphQLFloat,<br>  GraphQLList,<br>} = graphql;<br><br>// Import data models for products and orders.<br>const { Product } = require(&quot;../models/products&quot;);<br>const { Order } = require(&quot;../models/orders&quot;);<br><br>// Import user-defined data types for GraphQL.<br>const ProductType = require(&quot;./TypeDefs/ProductType&quot;);<br>const UserType = require(&quot;./TypeDefs/UserType&quot;);<br>const OrderType = require(&quot;./TypeDefs/OrderType&quot;);<br><br>// Define the RootQuery, which is the entry point for querying data.<br>const RootQuery = new GraphQLObjectType({<br>  name: &quot;RootQueryType&quot;,<br>  fields: {<br>    // Products Queries<br>    getAllProduct: {<br>      type: new GraphQLList(ProductType), // Define the type of data to be returned (a list of products).<br>      args: { id: { type: GraphQLString } }, // Specify any input arguments that can be used in the query (in this case, an &#39;id&#39;).<br>      async resolve(parent, args) {<br>        // The &#39;resolve&#39; function specifies how to fetch and return the requested data.<br>        // In this case, it fetches and returns a list of all products.<br>        const productList = await Product.find();<br>        return productList;<br>      },<br>    },<br>    getProduct: {<br>      type: ProductType, // Define the type of data to be returned (a single product).<br>      args: { id: { type: GraphQLString } }, // Specify an input argument &#39;id&#39;.<br>      async resolve(parent, args) {<br>        // The &#39;resolve&#39; function fetches and returns a specific product based on the provided &#39;id&#39;.<br>        const product = await Product.findById(args.id);<br>        return product;<br>      },<br>    },<br><br>    // Orders Queries<br>    getAllOrders: {<br>      type: new GraphQLList(OrderType), // Define the type of data to be returned (a list of orders).<br>      args: { id: { type: GraphQLString } }, // Specify an input argument &#39;id&#39;.<br>      async resolve(parent, args, req) {<br>        // The &#39;resolve&#39; function fetches and returns a list of orders for a specific user, but only if the user is authenticated.<br>        if (!req.isAuth) {<br>          throw new Error(&quot;Unauthenticated&quot;);<br>        }<br>        const orderList = await Order.find({ userId: args.id });<br>        return orderList;<br>      },<br>    },<br>  },<br>});<br><br>// Export a GraphQLSchema that includes the RootQuery.<br>module.exports = new GraphQLSchema({<br>  query: RootQuery,<br>});</pre><p><strong>Root Queries</strong>:</p><ul><li>The <strong>RootQuery</strong> is the entry point for querying data. It&#39;s like the main menu of options you have when you want to retrieve information.</li><li>In this code, we have defined several queries for retrieving data, such as <strong>getAllProduct</strong>, <strong>getProduct</strong>, and <strong>getAllOrders</strong>. These queries specify what data we can request.</li></ul><p><strong>Fields</strong>:</p><ul><li>Within the <strong>RootQuery</strong>, each query is defined as a &quot;field.&quot; For example, <strong>getAllProduct</strong>, <strong>getProduct</strong>, and <strong>getAllOrders</strong> are fields.</li><li>These fields specify the types of data they return and any input arguments they accept.</li></ul><p><strong>Types</strong>:</p><ul><li>GraphQL is strongly typed. Each query and the data it returns are defined by types. For example, <strong>ProductType</strong> and <strong>OrderType</strong> describe the structure of products and orders.</li></ul><p><strong>Resolvers</strong>:</p><ul><li>The <strong>resolve</strong> functions are responsible for fetching and returning the actual data when a query is executed. They determine how to retrieve the requested information from a database or other data source.</li></ul><p><strong>Input Arguments</strong>:</p><ul><li>Queries can accept input arguments to customize the results. For example, you can use the <strong>id</strong> argument to specify which product or order you want to retrieve.</li></ul><p>Now we created the schemas and our root queries let’s add our endpoint in the <strong>index.js:</strong></p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const mongoose = require(&quot;mongoose&quot;);<br>const PORT = 5000;<br>const { graphqlHTTP } = require(&quot;express-graphql&quot;);<br>const schema = require(&quot;./Schemas&quot;);<br><br>mongoose<br>  .connect(&quot;mongodb://127.0.0.1/{Your db collection name}&quot;)<br>  .then(() =&gt; console.log(&quot;Connected to MongoDB...&quot;))<br>  .catch((err) =&gt; console.error(&quot;Could not connect to MongoDB...&quot;));<br><br>app.use(<br>  &quot;/graphql&quot;,<br>  graphqlHTTP({<br>    schema,<br>    graphiql: true,<br>  })<br>);<br><br>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>Having defined our queries, the next step is to interact with our database by adding, updating, or deleting data. In GraphQL, this task is addressed using mutations. Mutations provide a mechanism to modify the data within the server. They allow clients to create, edit, or remove records while ensuring a consistent and controlled way to perform write operations.</p><p>Let’s back to <strong>index.js</strong> where we defined the queries and add some mutations:</p><pre>...<br>const Mutation = new GraphQLObjectType({<br>  name: &quot;Mutation&quot;,<br>  fields: {<br>    //Product mutations<br>    createProduct: {<br>      type: ProductType,<br>      args: {<br>        brand: { type: GraphQLString },<br>        category: { type: GraphQLString },<br>        description: { type: GraphQLString },<br>        discountPercentage: { type: GraphQLFloat },<br>        images: { type: GraphQLString },<br>        price: { type: GraphQLFloat },<br>        rating: { type: GraphQLFloat },<br>        stock: { type: GraphQLInt },<br>        thumbnail: { type: GraphQLString },<br>        title: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        const newProduct = new Product({<br>          title: args.title,<br>          brand: args.brand,<br>          category: args.category,<br>          description: args.description,<br>          discountPercentage: args.discountPercentage,<br>          images: args.images,<br>          price: args.price,<br>          rating: args.rating,<br>          stock: args.stock,<br>          thumbnail: args.thumbnail,<br>        });<br><br>        await newProduct.save();<br><br>        return newProduct;;<br>      },<br>    },<br><br>    updateProduct: {<br>      type: ProductType,<br>      args: {<br>        id: { type: GraphQLString },<br>        brand: { type: GraphQLString },<br>        category: { type: GraphQLString },<br>        description: { type: GraphQLString },<br>        discountPercentage: { type: GraphQLFloat },<br>        images: { type: GraphQLString },<br>        price: { type: GraphQLFloat },<br>        rating: { type: GraphQLFloat },<br>        stock: { type: GraphQLInt },<br>        thumbnail: { type: GraphQLString },<br>        title: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        const newProduct = await Product.findByIdAndUpdate(args.id, {<br>          brand: args.brand,<br>          category: args.category,<br>          description: args.description,<br>          discountPercentage: args.discountPercentage,<br>          images: args.images,<br>          price: args.price,<br>          rating: args.rating,<br>          stock: args.stock,<br>          thumbnail: args.thumbnail,<br>          title: args.title,<br>        });<br><br>        return newProduct;<br>      },<br>    },<br><br>    deleteProduct: {<br>      type: ProductType,<br>      args: {<br>        id: { type: GraphQLString },<br>      },<br>      async resolve(parent, args) {<br>        console.log(args.id);<br><br>        const deletedProduct = await Product.findByIdAndDelete(args.id);<br><br>        return args;<br>      },<br>    },<br>    <br>}});<br><br>module.exports = new GraphQLSchema({<br>  query: RootQuery,<br>  mutation: Mutation, //add mutations here<br>});</pre><ol><li><strong>Create Product Mutation</strong>:</li></ol><ul><li>The <strong>createProduct</strong> mutation allows you to add a new product to the database.</li><li>It accepts various product details as arguments, such as brand, category, description, and price.</li><li>It creates a new product using the provided arguments and saves it to the database.</li><li>Finally, it returns the details of the newly created product.</li></ul><p><strong>2. Update Product Mutation</strong>:</p><ul><li>The <strong>updateProduct</strong> mutation is used to modify an existing product in the database.</li><li>It takes the product’s ID along with various details (e.g., brand, category, and price) as arguments.</li><li>It finds the existing product by its ID and updates its details with the provided arguments.</li><li>The updated product details are then returned.</li></ul><p><strong>3. Delete Product Mutation</strong>:</p><ul><li>The <strong>deleteProduct</strong> mutation is designed to remove a product from the database.</li><li>It requires the product’s ID as an argument.</li><li>It deletes the product with the specified ID from the database.</li><li>The mutation returns the ID of the deleted product.</li></ul><p>Now that we have everything set up for interacting with GraphQL, it’s fortunate that GraphQL provides an excellent interface called GraphiQL. By visiting the <a href="http://localhost:5000/graphql">http://localhost:5000/graphql</a> endpoint, you can easily explore and interact with your data. Here are some cool features of GraphiQL.</p><p>You can learn more from here: <a href="https://www.gatsbyjs.com/docs/how-to/querying-data/running-queries-with-graphiql/">https://www.gatsbyjs.com/docs/how-to/querying-data/running-queries-with-graphiql/</a></p><p><strong>GraphiQL Features</strong>:</p><ol><li><strong>Interactive Interface</strong>: GraphiQL provides a web-based, interactive environment where you can compose and send GraphQL queries and mutations.</li><li><strong>Auto-Complete and Documentation</strong>: It offers auto-complete suggestions for query and mutation fields and displays documentation about your GraphQL schema, making it easy to explore the available data and operations.</li><li><strong>History and Presets</strong>: You can save and reuse previous queries and share them with your team. It’s a handy feature for iterative development.</li><li><strong>Real-Time Validation</strong>: GraphiQL provides instant feedback on query and mutation syntax errors, helping you avoid common mistakes.</li><li><strong>Responsive and Customizable</strong>: The interface is responsive, works well on various screen sizes, and can be customized to suit your needs.</li></ol><p>Let’s first add some data into our database:</p><ol><li><strong>Creating a New Product:</strong></li></ol><pre>mutation {<br>  createProduct(<br>    title: &quot;First Product&quot;,<br>    brand: &quot;Example Brand&quot;,<br>    category: &quot;Electronics&quot;,<br>    description: &quot;A new product description.&quot;,<br>    discountPercentage: 5,<br>    images: &quot;image path&quot;,<br>    price: 299.99,<br>    rating: 4.7,<br>    stock: 5,<br>    thumbnail: &quot;thumbnail path&quot;,<br>  ) {<br>    id<br>    title<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REWBphvPD1CVF-hVc_X8ow.png" /></figure><p>This mutation adds a new product with the specified details and returns the<strong> id</strong> and title of the newly created product.</p><p>2. <strong>Updating and existing product</strong></p><pre>mutation {<br>  updateProduct(id:&quot;653fbae451de02c94aef4382&quot;, description: &quot;Update description for the first product&quot;){<br>    id,<br>    description,<br>    title<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0EKDTgpkWxDDYyqSMyecQ.png" /></figure><p>This mutation modifies the description of the product with the given<strong> id </strong>and returns the<strong> id</strong>, <strong>title and the updated description</strong>.</p><p>3. <strong>Deleting a product</strong></p><pre>mutation{<br>  deleteProduct(id:&quot;653fbae451de02c94aef4382&quot;){<br>    id<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRnnDuHvvcYurLRGa3JZGQ.png" /></figure><p>Now that we have successfully used our mutations, it’s time to try out our queries. First, I have added three new products to the database.</p><p>Query to get all products from database:</p><pre>query{<br>  getAllProduct{<br>    id,<br>    title,<br>    brand<br>  }<br>}</pre><p><strong>Here is one of the great advantages of GraphQL: you can choose precisely what data you want to retrieve from the database. In this case, I am requesting the product’s ID, title, and brand to be returned.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqwwv83D3kLocK1BCZMnWA.png" /></figure><p>Query to get a specific product by<strong> ID</strong>:</p><pre>query {<br>  getProduct(id: &quot;653fcc789b3cf5f5cfa3e48d&quot;) {<br>    id<br>    title<br>    brand<br>    category<br>    description<br>    price<br>    stock<br>  }<br>}</pre><p>Here also you can choose what data you want to retrieve from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYy23fQlq30CnZ_lsPPjHA.png" /></figure><p>Now we’ve gained some insight into using GraphQL with Node.js. However, this is only the beginning. As you can see, the significant advantage lies in using just <strong>one URL</strong> for all operations, and the ability to dynamically determine the data we want from the database.</p><p>I hope this served as a good introduction to GraphQL. In the next part, I will introduce the authentication method with GraphQL and create the order mutation. You can find the full code<a href="https://github.com/tokosbence/Node-js-and-GraphQL"><strong> on GitHub</strong></a>.</p><p><a href="https://medium.com/@tokosbex/node-js-and-graphql-part-2-14583be41620"><strong>See you in the next part!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f54669498383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node js and GraphQL — Part 2]]></title>
            <link>https://medium.com/@tokosbex/node-js-and-graphql-part-2-14583be41620?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/14583be41620</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 19:23:52 GMT</pubDate>
            <atom:updated>2024-01-15T19:23:52.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL and Node js — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZTJDP3NkY0Zzag_eIEHCw.png" /><figcaption>GraphQL and Node Js</figcaption></figure><p><strong>Introduction</strong></p><p>Welcome back to our <strong>GraphQL</strong> journey! <strong>In part 2</strong>, we’re taking the next step by introducing authentication with <strong>GraphQL</strong> and showcasing the process of crafting order mutations. Let’s dive in!</p><p>As you saw in the first part we have a query for orders but to try that, first, we need to save our orders into the database. Let’s make the <strong>createOrder</strong> mutation:</p><pre>//Orders mutation<br>    createOrder: {<br>      type: GraphQLString,<br>      args: {<br>        userId: { type: GraphQLString },<br>        firstName: { type: GraphQLString },<br>        lastName: { type: GraphQLString },<br>        address: { type: GraphQLString },<br>        city: { type: GraphQLString },<br>        country: { type: GraphQLString },<br>        zipCode: { type: GraphQLString },<br>        totalAmount: { type: GraphQLFloat },<br>        items: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        console.log(args);<br>        const newOrder = new Order({<br>          userId: args.userId,<br>          firstName: args.firstName,<br>          lastName: args.lastName,<br>          address: args.address,<br>          city: args.city,<br>          country: args.country,<br>          zipCode: args.zipCode,<br>          totalAmount: args.totalAmount,<br>          items: args.items,<br>          createdDate: new Date().toLocaleDateString(),<br>        });<br><br>        await newOrder.save();<br>        const data = {<br>          message: &quot;success&quot;,<br>        };<br><br>        return JSON.stringify(data);<br>      },<br>    },</pre><p>Note! Here in the items field we expect a<strong> stringify array</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MA91x5S7ayu6ctK7nDHxBg.png" /></figure><p>Here as you see we get back the message that we defined in our mutation but you can retrieve any order attributes.</p><p>To generate a password hash, we must first install the <strong>bcrypt</strong> library. Hashing the password is a crucial method for securely storing passwords in the database, effectively preventing unauthorized individuals from accessing the actual password and adding an extra layer of security.</p><pre>npm install bcrypt</pre><p>Now let’s create the user mutations. Add the following code under the other mutations:</p><pre>//don&#39;t forget to import the bcrypt package<br>const bcrypt = require(&quot;bcrypt&quot;)<br><br><br>//Users mutations<br>    createUser: {<br>      type: GraphQLString,<br>      args: {<br>        username: { type: GraphQLString },<br>        email: { type: GraphQLString },<br>        password: { type: GraphQLString },<br>        isAdmin: { type: graphql.GraphQLBoolean },<br>      },<br>      async resolve(parent, args) {<br>        console.log(args);<br>        const newUser = new User({<br>          username: args.username,<br>          email: args.email,<br>          password: args.password,<br>          isAdmin: args.isAdmin,<br>        });<br><br>        const user = await User.findOne({ email: newUser.email });<br>        if (user) {<br>          throw new Error(&quot;Already in db&quot;);<br>        }<br><br>        const salt = await bcrypt.genSalt(10);<br>        newUser.password = await bcrypt.hash(newUser.password, salt);<br><br>        await newUser.save();<br>        const token = newUser.generateAuthToken();<br><br>        const data = {<br>          token: token,<br>          id: newUser.id,<br>          isAdmin: newUser.isAdmin,<br>        };<br>        return JSON.stringify(data);<br>      },<br>    },<br><br>    loginUser: {<br>      type: GraphQLString,<br>      args: {<br>        email: { type: GraphQLString },<br>        password: { type: GraphQLString },<br>      },<br>      async resolve(parent, args) {<br>        const user = await User.findOne({ email: args.email });<br>        if (!user) {<br>          throw new Error(&quot;Not user with that email&quot;);<br>        }<br>        const validPassword = await bcrypt.compare(<br>          args.password,<br>          user.password<br>        );<br><br>        if (!validPassword) {<br>          throw new Error(&quot;Invalid password&quot;);<br>        }<br>        const token = user.generateAuthToken();<br>        const data = {<br>          token: token,<br>          userId: user.id,<br>          isAdmin: user.isAdmin,<br>        };<br>        return JSON.stringify(data);<br>      },<br>    },</pre><p><strong>1. createUser Mutation</strong>:</p><ul><li>This mutation is used for creating a new user in your application.</li><li>It accepts several input arguments, including <strong>username</strong>, <strong>email</strong>, <strong>password</strong>, and <strong>isAdmin</strong>.</li><li>In the <strong>resolve</strong> function, a new user object is created based on the provided arguments.</li><li>It checks if a user with the same email already exists in the database. If one is found, it throws an error.</li><li>It generates a random <strong>“salt”</strong> and uses it to hash the user’s password for security.</li><li>The new user is then saved to the database, and an authentication token is generated for the user.</li><li>The result of this mutation is a JSON string containing the authentication token, user ID, and isAdmin status.</li></ul><p><strong>2. loginUser Mutation</strong>:</p><ul><li>This mutation is used for authenticating and logging in a user.</li><li>It takes <strong>email</strong> and <strong>password</strong> as input arguments.</li><li>In the <strong>resolve</strong> function, it searches for a user with the provided email in the database. If no user is found, it throws an error.</li><li>It then checks if the provided password matches the stored hashed password using <strong>bcrypt.compare</strong>. If the password is invalid, it throws an error.</li><li>If the user is successfully authenticated, an authentication token is generated for the user.</li><li>The result of this mutation is a JSON string containing the authentication token, user ID, and isAdmin status.</li></ul><p>These mutations are fundamental for user registration and login, ensuring the secure storage and validation of user credentials. The generated authentication tokens can be used to authorize and authenticate users in your application.</p><p>But before using these methods we need to little bit modify our user models. First, install the<strong> jsonwebtoken</strong> library.</p><pre>npm i jsonwebtoken</pre><p>The <strong>jsonwebtoken</strong> npm package is a library for creating and verifying JSON Web Tokens (JWT). JWTs are a compact, self-contained way to represent information between parties securely. They are often used for user authentication and authorization in web applications. With <strong>jsonwebtoken</strong>, you can create JWTs that encode user data and claims, and verify them to ensure their authenticity and integrity. This package is commonly used for implementing user authentication and authorization in web applications.</p><p>Let’t add this function for the user model:</p><pre>userSchema.methods.generateAuthToken = function () {<br>  const token = jwt.sign(<br>    { _id: this._id, isAdmin: this.isAdmin },<br>    &quot;jwtPrivateKey&quot; <br>  );<br>  return token;<br>};</pre><p><strong>1. userSchema.methods.generateAuthToken = function () {</strong></p><ul><li>This function is added to the <strong>userSchema</strong> as a method, which means it can be called on a user instance.</li></ul><p><strong>2. const token = jwt.sign( { _id: this._id, isAdmin: this.isAdmin }, &quot;jwtPrivateKey&quot;);</strong></p><ul><li>It uses the <strong>jwt.sign</strong> method from the <strong>jsonwebtoken</strong> library to create a JWT.</li><li>The first argument to <strong>jwt.sign</strong> is an object containing the data you want to include in the token. In this case, it typically includes the user&#39;s ID (<strong>_id</strong>) and their admin status (<strong>isAdmin</strong>).</li><li>The second argument is a secret key, usually referred to as a “JWT secret.” It should be stored securely and kept secret, typically in an environment variable. It’s important to use a strong, complex key for security.</li></ul><p><strong>3. return token;</strong></p><ul><li>Finally, the function returns the generated token, which can be used for authenticating and authorizing the user. The token contains the user’s data and a digital signature to verify its authenticity.</li></ul><p>We defined the functions so now we can try the <strong>createUser</strong> mutation which is the sign-up function.</p><pre>mutation{<br>  createUser(username:&quot;testUsername&quot;, <br>             email:&quot;test@gmail.com&quot;, <br>             password: &quot;testPassword&quot;, <br>             isAdmin: false)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TpVg1jUtJNEW-K9Drc-BA.png" /></figure><p>Voilà! We’ve obtained the token, user ID, and the isAdmin field.</p><p>Next, let’s test the <strong>loginUser</strong> mutation:</p><pre>mutation{<br>  loginUser( email:&quot;test@gmail.com&quot;, password: &quot;testPassword&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b-GdEuL8Ildl5ebFP14Lg.png" /></figure><p>And we receive the same data as in the<strong> signIn </strong>method. Our final step is to create the authentication middleware, which can be used to secure our mutations and queries.</p><p>To do this, let’s create a folder named<strong> “middleware”</strong> and add a file called <strong>“auth.js”</strong></p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>const config = require(&quot;config&quot;);<br><br>function isAuth(req, res, next) {<br>  const authHeader = req.get(&quot;Authorization&quot;);<br>  if (!authHeader) {<br>    req.isAuth = false;<br>    return next();<br>  }<br><br>  const token = authHeader.split(&quot; &quot;)[1];<br>  if (!token || token === &quot;&quot;) {<br>    {<br>      req.isAuth = false;<br>      return next();<br>    }<br>  }<br><br>  try {<br>    const decoded = jwt.verify(token, config.get(&quot;jwtPrivateKey&quot;));<br>    req.user = decoded;<br>    req.isAuth = true;<br>    next();<br>  } catch (ex) {<br>    req.isAuth = false;<br>    next();<br>  }<br>}<br><br>module.exports = isAuth;</pre><ul><li>When a request arrives, the <strong>isAuth</strong> function first attempts to retrieve the &quot;Authorization&quot; header from the request. This header often contains a JSON Web Token (JWT) that verifies a user&#39;s identity.</li><li>If there’s no “Authorization” header, it means the user is not authenticated. In this case, the <strong>req.isAuth</strong> property is set to <strong>false</strong>, and the request is allowed to continue through the subsequent middleware or route handlers without authentication.</li><li>If an “Authorization” header exists, the function extracts the JWT from the header, typically in the format “Bearer &lt;token&gt;”. It checks if the token exists and is not empty.</li><li>If no valid token is found, or if the token is empty, the user is considered unauthenticated. The <strong>req.isAuth</strong> property is set to <strong>false</strong>, and the request continues without authentication.</li><li>If a valid token is present, the function proceeds to verify the token’s authenticity using <strong>jwt.verify</strong>. This method checks the token&#39;s validity and ensures it hasn&#39;t been tampered with.</li><li>If the token is successfully verified, it is decoded to access user-related data, such as the user’s ID and potentially other information. This data is attached to the <strong>req</strong> object, making it available for use in subsequent parts of the application.</li><li>The <strong>req.isAuth</strong> property is set to <strong>true</strong>, indicating that the user is authenticated.</li><li>Regardless of whether the token verification succeeds or not, the middleware always calls <strong>next()</strong> to allow the request to continue processing through subsequent middleware or reach the designated route handler.</li><li>If there’s an error during token verification, such as an invalid or expired token, the middleware catches the exception. In this case, the user is considered unauthenticated (req.isAuth = false), and the request continues to be processed.</li></ul><p>In essence, this middleware ensures that incoming requests are checked for valid JWTs, and authenticated users can access protected resources while unauthenticated users can proceed without authentication.</p><p>Add the middleware function to our <strong>main index.js</strong> file:</p><pre>const isAuth = require(&quot;./middleware/auth&quot;);<br>...<br>//before our endpoint<br>app.use(isAuth);</pre><p>See it in action. If you want to secure your <strong>“getAllProduct”</strong> query, you can add the following line (Note: It’s important to add the <strong>“req”</strong> attribute to the resolve function):</p><pre>getAllProduct: {<br>      type: new GraphQLList(ProductType), <br>      args: { id: { type: GraphQLString } },<br>      async resolve(parent, args ,req) {<br>        <br>    if (!req.isAuth) {<br>          throw new Error(&quot;Unauthenticated&quot;);<br>        }<br>       <br>        const productList = await Product.find();<br>        return productList;<br>      },<br>    },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40DmU-sm88AyClMtkM6ocQ.png" /></figure><p>Here’s what we’ve learned:</p><ol><li><strong>GraphQL</strong>: We’ve delved into GraphQL, a powerful query language and runtime for APIs, understanding how it enables efficient data retrieval and modification by allowing clients to request precisely what they need.</li><li><strong>User Authentication</strong>: We’ve implemented user authentication, a fundamental aspect of web applications, using JSON Web Tokens (JWTs). We’ve seen how to create, verify, and use JWTs to authenticate and authorize users securely.</li><li><strong>Database Interaction</strong>: We’ve interacted with databases, including MongoDB, for storing and retrieving data. We’ve learned how to create, update, and delete data using GraphQL mutations.</li><li><strong>Middleware</strong>: We’ve explored the concept of middleware in Node.js, understanding how it allows us to execute code during the request-response cycle, enabling tasks like authentication and data processing.</li><li><strong>Security Best Practices</strong>: We’ve emphasized the importance of security best practices, such as hashing user passwords and keeping sensitive information, like JWT secrets, confidential and securely stored.</li></ol><p>Thank you for reading this brief tutorial on connecting <strong>Node.js</strong> and <strong>GraphQL</strong>. I hope you found it enjoyable and insightful. If you have any questions or find anything confusing, you can refer to the <a href="https://github.com/tokosbence/Node-js-and-GraphQL"><strong>GitHub repository here</strong>.</a> Additionally, if you’re interested in learning more about <a href="https://medium.com/@tokosbex/creating-an-e-commerce-site-with-mern-stack-part-i-5d8c4379a88a"><strong>MERN stack applications, you can explore my other tutorials</strong></a>.</p><p><strong>See you soon!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14583be41620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an E-commerce Site with MERN Stack — Part I]]></title>
            <link>https://medium.com/@tokosbex/creating-an-e-commerce-site-with-mern-stack-part-i-5d8c4379a88a?source=rss-a94880eb88a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d8c4379a88a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[e-commerce-software]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Tókos Bence]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 17:11:30 GMT</pubDate>
            <atom:updated>2024-01-15T17:11:30.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating an E-commerce Site with MERN Stack — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*EOIVwKmEMBHyaE-wKqkJEQ.png" /></figure><p><strong>A Step-by-Step MERN Stack Tutorial</strong></p><p><strong>Introduction</strong></p><p>MERN stack is a popular web development technology stack used for building scalable and efficient web applications. It consists of four key technologies: MongoDB, Express.js, React, and Node.js.</p><ul><li><strong>Mongo DB </strong>is a document-based database, which means that data is stored in flexible JSON-like documents instead of tables with rows and columns. (<a href="https://www.mongodb.com/">https://www.mongodb.com/</a>)</li><li><strong>Express.js</strong> is a flexible and lightweight backend web application framework built on top of Node.js (<a href="https://expressjs.com/">https://expressjs.com/</a>)</li><li><strong>React.js</strong> is a powerful frontend JavaScript library for building user interfaces also React’s reusable components make it easier to develop complex user interfaces and enable faster rendering of dynamic content. (<a href="https://legacy.reactjs.org/">https://legacy.reactjs.org/</a>)</li><li><strong>Node.js </strong>is a JavaScript runtime that allows us to run JavaScript on the server-side. (<a href="https://nodejs.org/en">https://nodejs.org/en</a>)</li></ul><p><strong>E-commerce</strong> has become an integral part of our lives, and building an e-commerce website requires expertise in web development.</p><p>Together, these four technologies provide a comprehensive and powerful solution for building a modern e-commerce website. <strong>MERN</strong> stack allows developers to build highly responsive, efficient, and dynamic applications using a single programming language (JavaScript) and a consistent set of technologies.</p><p><strong>Benefits of using MERN Stack for e-commerce</strong></p><p>The <strong>MERN</strong> stack provides a comprehensive and cohesive solution for building modern web applications. It allows developers to use a single programming language, JavaScript, for both the frontend and backend of an application. This makes it easier to build and maintain complex web applications, as developers do not need to switch between different programming languages and tools. Additionally, the <strong>MERN</strong> stack provides a set of powerful and flexible technologies that can be used to build highly responsive and scalable applications.</p><p><strong>Setting up the environments</strong></p><p><strong>Step 1: Installing Node.js and React</strong></p><p>To get started with building, first, we need to install Node.js (if we have not already installed it) and React. For the installation, we use the Node Package Manager (npm) by running the following commands:</p><pre>npm install -g node<br>npx create-react-app &lt;your-app-name&gt;</pre><p>The first command installs Node.js globally on our system. The second command creates a new React project.</p><p><strong>Step 2: Setting up the Server-Side Application (Backend)</strong></p><p>First, create a folder for the backend part, and inside the folder, we can easily create an npm project using the following command:</p><pre>npm init -y</pre><p>After we ran the command in our backend folder, it already created the package.json file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*MfqaJebL3ReONg2RfeYadQ.png" /><figcaption>The project name will be different, it depends on how you named your folder.</figcaption></figure><p>Here, we can change the project name, decide on a specific version, and add a project description. Initially, our main file is called index.js. So, go to the project folder and create an empty index.js file. After we initialize the package.json file, we can easily install different packages for the project.</p><p>The first package we need to install is Express.js. Express is a popular Node.js framework for building server-side applications. Run the following command inside the backend folder:</p><pre>npm install --save express</pre><p>This command installs the Express package and saves it as a dependency in our project’s package.json file.</p><p><strong>Index.js</strong></p><p>Add the following code to the index.js file:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = 5000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello World!&#39;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>});</pre><p>This code sets up a simple Express server that listens on port 5000 and responds with “Hello World!” when we access the root URL. Go to your browser and check it yourself (<a href="http://localhost:5000/">http://localhost:5000/</a>).</p><p><strong>Step 3: Installing MongoDB and Mongoose</strong></p><p>Finally, we need to install MongoDB and Mongoose to connect to the database. You can download it from the official site ( <a href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/">https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/</a>) and install it. MongoDB Compass helps us manage our databases. Mongoose is an Object-Document Mapping (ODM) library for MongoDB that provides a schema-based solution to model our data.</p><pre>npm install --save mongoose</pre><p>This command installs the Mongoose packages and saves them as dependencies in our project’s package.json file</p><p><strong>Conclusion</strong></p><p>To sum up, this article has demonstrated the process of setting up an environment for building an e-commerce website with the MERN Stack. After following the steps, the necessary folders for the frontend and backend parts are created, and we have successfully installed Node.js, React, Express, MongoDB, and Mongoose. With this foundation in place, we are now equipped to begin building our e-commerce website. I hope that these instructions have been helpful in getting your project started, and I encourage you to check out <a href="https://medium.com/@tokosbex/creating-an-e-commerce-site-with-mern-stack-part-ii-d6fd908c7151"><strong>part II</strong></a> of this series, where we dive into the actual building process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d8c4379a88a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>