<?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 Purti Aggarwal on Medium]]></title>
        <description><![CDATA[Stories by Purti Aggarwal on Medium]]></description>
        <link>https://medium.com/@purtiaggarwal1997?source=rss-2cd25a483a9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uUySRdl7rrETGB81GBdOHg.jpeg</url>
            <title>Stories by Purti Aggarwal on Medium</title>
            <link>https://medium.com/@purtiaggarwal1997?source=rss-2cd25a483a9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:38:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@purtiaggarwal1997/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[How to Build an AI Agent for Auto Instagram Posting using the MERN Stack]]></title>
            <link>https://purtiaggarwal1997.medium.com/how-to-build-an-ai-agent-for-auto-instagram-posting-using-the-mern-stack-ba5f08874dbf?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba5f08874dbf</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 13:16:18 GMT</pubDate>
            <atom:updated>2025-10-05T13:16:18.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T--PXHt9U73F2Jh7TrG1qg.png" /></figure><p>Want an autonomous assistant that generates captions/images and posts to Instagram on a schedule? This guide walks you through a production-ready approach using <strong>MERN</strong> (MongoDB, Express, React, Node). I’ll give architecture, required accounts and permissions, a clear stepwise implementation, sample code snippets, security notes and ideas for scaling. Let’s go 🚀</p><h3>What you’ll build (high level)</h3><ul><li><strong>Backend (Node/Express)</strong> — exposes APIs to create posts, ask the AI to generate captions/images, saves scheduled posts to MongoDB, and publishes to Instagram using the <strong>Instagram Graph API</strong>.</li><li><strong>Scheduler</strong> — a small worker (cron or job queue) that picks scheduled posts and publishes them.</li><li><strong>Frontend (React)</strong> — UI to create/edit posts, preview AI-generated captions/images, schedule publishing or publish immediately.</li><li><strong>Storage (MongoDB)</strong> — stores posts, logs, user settings, tokens and publish history.</li><li><strong>AI</strong> — use an LLM (OpenAI or another provider) for captions + hashtag suggestions; optionally use an image generation API for images.</li></ul><h3>Prerequisites &amp; accounts</h3><p><strong>Developer accounts</strong></p><ul><li>Facebook Developer account &amp; <strong>Facebook App</strong> (to use Instagram Graph API).</li><li>Instagram <strong>Business</strong> or <strong>Creator</strong> account connected to a Facebook Page (required for publishing).</li><li>OpenAI (or other LLM/image API) API key for caption/image generation.</li></ul><p><strong>Dev tools</strong></p><ul><li>Node.js (16+ recommended)</li><li>npm or yarn</li><li>MongoDB Atlas (or local MongoDB)</li><li>Git, code editor</li></ul><p><strong>Permissions / API notes</strong></p><ul><li>Instagram Graph API permissions required for posting: instagram_basic, pages_show_list, instagram_content_publish, etc. (You must go through Facebook App review to use these permissions in production.)</li><li>Instagram long-lived access tokens are recommended for automated publishing; manage token refresh.</li></ul><h3>Folder structure (suggested)</h3><pre>insta-agent/<br>├─ backend/<br>│  ├─ src/<br>│  │  ├─ controllers/<br>│  │  ├─ services/<br>│  │  ├─ models/<br>│  │  ├─ routes/<br>│  │  └─ scheduler.js<br>│  ├─ server.js<br>│  └─ package.json<br>└─ frontend/<br>   ├─ src/<br>   │  ├─ components/<br>   │  ├─ pages/<br>   │  └─ api.js<br>   └─ package.json</pre><h3>Lets Dive In Backend</h3><h3>1) Environment variables (.env.template)</h3><pre># Backend<br>PORT=5000<br>MONGO_URI=mongodb+srv://&lt;user&gt;:&lt;pass&gt;@cluster.../insta-agent<br>OPENAI_API_KEY=sk-xxxx<br>OPENAI_MODEL=gpt-4o<br>IG_USER_ID=&lt;instagram-user-id&gt;<br>IG_API_VERSION=v17.0<br>IG_ACCESS_TOKEN=&lt;long-lived-access-token&gt;<br>FRONTEND_URL=http://localhost:3000<br>JWT_SECRET=supersecret</pre><h3>2) Backend — packages to install</h3><pre>npm init -y<br>npm i express mongoose axios dotenv node-cron cors multer bcrypt jsonwebtoken<br># If you prefer OpenAI official client:<br>npm i openai</pre><h3>3) MongoDB model — Post (example)</h3><pre>// models/Post.js<br>const mongoose = require(&#39;mongoose&#39;);<br><br>const PostSchema = new mongoose.Schema({<br>  caption: String,<br>  imageUrl: String,          // hosted image URL (or generated image URL)<br>  scheduling: {<br>    publishAt: Date,         // when to publish<br>    timezone: String<br>  },<br>  status: { type: String, enum: [&#39;draft&#39;,&#39;scheduled&#39;,&#39;published&#39;,&#39;failed&#39;], default: &#39;draft&#39; },<br>  createdAt: { type: Date, default: Date.now },<br>  publishedAt: Date,<br>  igCreationId: String,      // creation id returned by IG when uploading a media<br>  logs: [String]<br>});<br><br>module.exports = mongoose.model(&#39;Post&#39;, PostSchema);</pre><h3>4) AI content generation service (backend)</h3><p><strong>Caption + hashtags (example using OpenAI chat completions via axios)</strong></p><pre>// services/aiService.js<br>const axios = require(&#39;axios&#39;);<br><br>async function generateCaption(prompt) {<br>  const res = await axios.post(&#39;https://api.openai.com/v1/chat/completions&#39;, {<br>    model: process.env.OPENAI_MODEL,<br>    messages: [{ role: &#39;user&#39;, content: prompt }],<br>    max_tokens: 150<br>  }, {<br>    headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` }<br>  });<br><br>  return res.data.choices[0].message.content.trim();<br>}<br><br>module.exports = { generateCaption };</pre><p><strong>Image generation</strong></p><ul><li>Option A: Use an image generation API (OpenAI images endpoint, DALL·E, Stability, Replicate) and return an image URL.</li><li>Option B: Upload a user image (Multer) and use it as-is or apply edits with an image editing API.</li></ul><h3>5) Instagram posting service (backend)</h3><p><strong>Two-step flow (Graph API): create media object → publish it.</strong></p><pre>// services/instagramService.js<br>const axios = require(&#39;axios&#39;);<br><br>const IG_BASE = (version, userId) =&gt; `https://graph.facebook.com/${version}/${userId}`;<br><br>async function createMedia(image_url, caption) {<br>  const url = `${IG_BASE(process.env.IG_API_VERSION, process.env.IG_USER_ID)}/media`;<br>  const res = await axios.post(url, {<br>    image_url,<br>    caption,<br>    access_token: process.env.IG_ACCESS_TOKEN<br>  });<br>  return res.data; // { id: &#39;creation_id&#39; }<br>}<br><br>async function publishMedia(creation_id) {<br>  const url = `${IG_BASE(process.env.IG_API_VERSION, process.env.IG_USER_ID)}/media_publish`;<br>  const res = await axios.post(url, {<br>    creation_id,<br>    access_token: process.env.IG_ACCESS_TOKEN<br>  });<br>  return res.data; // contains published post id<br>}<br><br>module.exports = { createMedia, publishMedia };</pre><p><strong>Notes</strong></p><ul><li>Use image_url that the Graph API can fetch over the public internet.</li><li>For carousels or videos the flow changes slightly (carousel requires children param).</li></ul><h3>5) Posting endpoint example (create + publish immediately)</h3><pre>// routes/post.js<br>const express = require(&#39;express&#39;);<br>const Post = require(&#39;../models/Post&#39;);<br>const { generateCaption } = require(&#39;../services/aiService&#39;);<br>const { createMedia, publishMedia } = require(&#39;../services/instagramService&#39;);<br><br>const router = express.Router();<br><br>router.post(&#39;/ai-post&#39;, async (req, res) =&gt; {<br>  try {<br>    const { prompt, imageUrl, publishNow } = req.body;<br><br>    const caption = await generateCaption(prompt || &quot;Write an engaging Instagram caption about dropshipping tips.&quot;);<br>    const create = await createMedia(imageUrl, caption);<br>    const post = new Post({ caption, imageUrl, status: publishNow ? &#39;publishing&#39; : &#39;draft&#39; });<br>    await post.save();<br><br>    if (publishNow) {<br>      const pub = await publishMedia(create.id);<br>      post.status = &#39;published&#39;;<br>      post.publishedAt = new Date();<br>      post.igCreationId = create.id;<br>      await post.save();<br>      return res.json({ success: true, published: pub });<br>    }<br><br>    // saved as draft/scheduled<br>    post.igCreationId = create.id;<br>    await post.save();<br>    res.json({ success: true, post });<br>  } catch (err) {<br>    console.error(err);<br>    res.status(500).json({ error: &#39;Server error&#39; });<br>  }<br>});<br><br>module.exports = router;</pre><h3>6) Scheduler — publish scheduled posts automatically</h3><p>Use node-cron or a job queue (Agenda, BullMQ) for reliability/resilience. Example with node-cron checking every minute:</p><pre>// scheduler.js<br>const cron = require(&#39;node-cron&#39;);<br>const Post = require(&#39;./models/Post&#39;);<br>const { publishMedia } = require(&#39;./services/instagramService&#39;);<br><br>cron.schedule(&#39;* * * * *&#39;, async () =&gt; {<br>  // find scheduled posts due now (with small buffer)<br>  const now = new Date();<br>  const duePosts = await Post.find({ status: &#39;scheduled&#39;, &#39;scheduling.publishAt&#39;: { $lte: now }});<br>  for (const p of duePosts) {<br>    try {<br>      const result = await publishMedia(p.igCreationId);<br>      p.status = &#39;published&#39;;<br>      p.publishedAt = new Date();<br>      p.logs.push(`Published: ${JSON.stringify(result)}`);<br>      await p.save();<br>    } catch (err) {<br>      p.status = &#39;failed&#39;;<br>      p.logs.push(`Publish failed: ${err.message}`);<br>      await p.save();<br>    }<br>  }<br>});</pre><p><strong>Better option for production:</strong> use job queues (BullMQ or Agenda) and persistent retries.</p><h3>7) Frontend (React) — features to implement</h3><ul><li><strong>New Post</strong> form: Upload image OR provide image URL, select “Use AI caption” (shows preview), edit caption, add hashtags.</li><li><strong>Schedule</strong> control: pick date/time/timezone.</li><li><strong>Queue &amp; History:</strong> show scheduled &amp; published posts.</li><li><strong>Auth:</strong> Simple JWT login for multiple team members (optional).</li><li><strong>Preview:</strong> show how the post will look.</li></ul><p><strong>API call example (frontend → backend)</strong></p><pre>// src/api.js (React)<br>import axios from &#39;axios&#39;;<br>export const createAIPost = (payload) =&gt; axios.post(&#39;/api/posts/ai-post&#39;, payload);</pre><p><strong>Example component usage</strong></p><pre>// NewPostForm.jsx<br>const onSubmit = async () =&gt; {<br>  await createAIPost({ prompt: &quot;Create a motivational caption for ecommerce sellers&quot;, imageUrl, publishNow: true });<br>  // show success<br>};</pre><h3>8) Security, compliance and best practices</h3><ul><li><strong>Store tokens securely:</strong> Never commit tokens. Use environment variables and secrets manager for production. Rotate tokens and use long-lived tokens with refresh strategy.</li><li><strong>Rate limiting &amp; backoff:</strong> Instagram &amp; AI APIs have rate limits. Implement retry with exponential backoff.</li><li><strong>Human approval flow:</strong> For brand safety, include optional manual approval before publishing.</li><li><strong>Privacy:</strong> Don’t store sensitive PII. Follow GDPR/other relevant rules.</li><li><strong>Facebook App Review:</strong> For public use, you must submit for FB App review for required permissions.</li><li><strong>Log everything:</strong> Save API responses and errors for debugging.</li></ul><h3>9) Deployment &amp; ops</h3><ul><li><strong>Frontend:</strong> Vercel, Netlify.</li><li><strong>Backend:</strong> Render, Heroku, AWS ECS, DigitalOcean App Platform. Use a process manager (PM2) or Docker.</li><li><strong>DB:</strong> MongoDB Atlas.</li><li><strong>Cron/Worker:</strong> Run scheduler on backend host or a separate worker instance (recommended).</li><li><strong>Monitoring:</strong> Sentry + logs (Papertrail/LogDNA).</li></ul><h3>10) Extra features &amp; improvements</h3><ul><li>Multi-account support (multiple IG accounts &amp; pages).</li><li>Reels upload (video flow differs — requires video upload with staging and publish).</li><li>Auto-A/B caption testing + analytics to pick top performing captions.</li><li>Smart posting times (use engagement analytics to suggest publish time).</li><li>A/B image variants using AI image edits.</li><li>UI approval queue with roles (author/editor/publisher).</li></ul><h3>11) Quick checklist before going live</h3><ul><li>IG account is Business/Creator and linked to a Facebook Page</li><li>Facebook App created and necessary permissions requested</li><li>Long-lived access token obtained and stored securely</li><li>Rate limit &amp; retry logic implemented for both AI and IG APIs</li><li>Manual approval flow for first N posts (safety)</li><li>Logging and alerting in place</li></ul><h3>12) Sample .env to test locally</h3><pre>PORT=5000<br>MONGO_URI=mongodb://localhost/insta-agent<br>OPENAI_API_KEY=sk-test<br>OPENAI_MODEL=gpt-4o-mini<br>IG_USER_ID=178xxxxxxxxxxxx<br>IG_API_VERSION=v17.0<br>IG_ACCESS_TOKEN=EAABsbCS1...</pre><h3>13) Final tips &amp; closing</h3><ul><li>Start small: first build a minimal flow — <strong>generate caption → upload image → publish</strong>. Then add scheduling, image generation and approval.</li><li>Always test with a sandbox Instagram test account before using a production/brand account.</li><li>Keep logs and safe rollback for any mass posting features.</li></ul><p><strong>Happy Coding!</strong> 🚀</p><p>Read my other articles</p><ul><li><a href="https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d">Social Media Login Using NodeJs and PassportJs</a></li><li><a href="https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d">Social Media Login Using NodeJs and PassportJs</a></li><li><a href="https://purtiaggarwal1997.medium.com/how-to-deploy-reactjs-project-in-10-mins-9dfdbdee8f52">How to Deploy ReactJS Project in 10 Mins</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba5f08874dbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy ReactJS Project in 10 Mins]]></title>
            <link>https://purtiaggarwal1997.medium.com/how-to-deploy-reactjs-project-in-10-mins-9dfdbdee8f52?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfdbdee8f52</guid>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 20:16:51 GMT</pubDate>
            <atom:updated>2025-03-09T20:16:51.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, with ChatGPT generating code for us, the final step is deploying it to make it live and accessible to users.</p><p>Firebase Hosting provides a simple and efficient way to deploy your ReactJS applications with speed, security, and scalability. In this blog, I’ll go through a step-by-step guide on how to deploy a ReactJS app on Firebase.</p><h4>Let’s dive in!</h4><h3>Step 1: Create a Firebase Project</h3><p>Before deploying, we need to create a project in Firebase:</p><ol><li>Go to <a href="https://console.firebase.google.com/u/1/?pli=1">Firebase Console</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeck_1AdjwRH8icSJzoaDw.png" /></figure><p>2. Click on <strong>“Firebase project”</strong> and give it a name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srUkUWlxrOUjLyyKpD9b3w.png" /></figure><p>3. Choose whether to enable Google Analytics (optional).<br><strong>Google Analytics</strong> is a powerful web analytics tool offered by Google that helps website owners track and analyze user interactions on their websites or apps. It provides detailed insights into user behavior, traffic sources, engagement, and conversions, enabling businesses to make data-driven decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvJ7cLDgfZKQvKZJQh-7uw.png" /></figure><p>4. Click <strong>Create Project</strong> and wait for Firebase to set it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6JagZjT1BKMO746LS9GOA.png" /></figure><h3>Step 2: Install Firebase CLI</h3><p>To deploy your React app, you need to install the Firebase CLI:</p><ol><li>Install Firebase CLI globally using npm:</li></ol><pre>npm install -g firebase-tools</pre><p>2. Check if the installation was successful:</p><pre>firebase --version</pre><p>3. Log in to Firebase:</p><pre>firebase login</pre><p>This will open a browser asking for Firebase authentication. Sign in with your Google account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqKUUU-2psxURyWGdcBp2A.png" /></figure><h3>Step 3: Set Up Firebase in Your React Project</h3><p>This is the last step. Navigate to your React project folder and initialize Firebase:</p><ol><li>Open a terminal in your React project folder and run:</li></ol><pre>firebase init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybb23m8vkSpN9DNa4kea6g.png" /></figure><ol><li>Select <strong>Hosting</strong> using the arrow keys and press <strong>Space</strong> to choose it.</li><li>Choose <strong>Use an existing project</strong> and select the Firebase project you created earlier.</li><li>Specify the build folder (for React, it’s usually build).</li><li>Choose <strong>Yes</strong> when asked to configure it as a single-page app.</li><li>Opt <strong>No</strong> for automatic builds unless you want GitHub integration.</li></ol><h3>Step 4: Build and Deploy Your React App</h3><p>Once Firebase is set up, deploy your app:</p><ol><li>First, build your React project:</li></ol><pre>npm run build</pre><p>2. Deploy to Firebase:</p><pre>firebase deploy --</pre><p>3. Firebase will generate a <strong>Hosting URL</strong> where your React app is now live.</p><h3>Step 5: Updating the App</h3><p>Whenever you make changes and want to update the live version:</p><ol><li>Rebuild the project:</li></ol><pre>npm run build;</pre><ol><li>Deploy again:</li></ol><pre>firebase deploy;</pre><h3>Conclusion</h3><p>Deploying a ReactJS app on Firebase is straightforward and takes just a few commands. With Firebase Hosting, you get a fast, reliable, and secure way to make your project live. Now, go ahead and share your React app with the world!</p><p>Hopefully, this helps you with deploying code.</p><p><strong>Happy Coding!</strong> 🚀</p><p>Read my other articles</p><ul><li><a href="https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d">Social Media Login Using NodeJs and PassportJs</a></li><li><a href="https://medium.com/jsblend/how-to-send-emails-with-templates-using-nodejs-176b72c1406d">How to Send Emails With Templates using NodeJs</a></li><li><a href="https://medium.com/jsblend/image-upload-using-nodejs-16b1e804ec92">Image upload using NodeJs</a></li><li><a href="https://medium.com/aeologic/getting-started-with-nodejs-10e6180aea96">Getting started with NodeJs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfdbdee8f52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Start with NextJs]]></title>
            <link>https://purtiaggarwal1997.medium.com/getting-start-with-nextjs-dfdae6f8f1c8?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfdae6f8f1c8</guid>
            <category><![CDATA[next]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 15:18:49 GMT</pubDate>
            <atom:updated>2024-03-24T15:18:49.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGCTjeAh0b56-zJ6hoPZ8w.png" /><figcaption>NEXTJS</figcaption></figure><p><strong>NextJs</strong> is the best tool for <strong>ReactJs</strong> tool to learn and improve their skills.</p><p><strong>Next.js</strong> is a popular React framework used for building production-ready web applications. It supports server-side rendering (<strong>SSR</strong>) and static site generation (<strong>SSG</strong>), enabling fast page loads and better <strong>SEO</strong> performance. Next.js simplifies complex tasks like routing, data fetching, and code splitting, allowing developers to focus on building features. It offers built-in CSS and Sass support, as well as automatic code splitting for optimized performance. Next.js provides a variety of deployment options, including hosting on platforms like <strong>Vercel, Netlify, and AWS</strong>.</p><h3>PROs &amp; CONs of NEXTJS</h3><h4>Pros</h4><ul><li><strong>Page-based routing</strong>: Next.js enables developers to create pages by placing components within the /pages directory, allowing for easy organization and navigation within the application.</li><li><strong>Integrated router</strong>: Next.js includes its own router, eliminating the need for developers to install additional libraries like React Router. This built-in router simplifies the process of defining routes and handling navigation within the application.</li><li><strong>API routes</strong>: With Next.js, developers can write backend code using Node.js directly within the /pages/api directory. This feature allows for seamless integration of server-side logic alongside client-side code.</li><li><strong>Fast builds</strong>: Next.js provides super-fast build times for both development and production environments. Developers can see their changes reflected instantly, facilitating a smooth and efficient development workflow.</li><li><strong>Image and font optimization</strong>: Next.js offers built-in optimization features for images and fonts, ensuring optimal performance and load times for web applications. This helps improve the overall user experience and SEO ranking of the site.</li><li><strong>ESLint and TypeScript support</strong>: Next.js comes with built-in support for ESLint and TypeScript, helping developers write cleaner and more maintainable code. This ensures code quality and reduces the likelihood of errors or bugs in the application.</li><li><strong>Additional features</strong>: Next.js boasts a wide range of additional features and capabilities, all of which are detailed in the official <a href="https://nextjs.org/docs"><strong><em>Next.js documentation</em></strong></a>. These include but are not limited to server-side rendering, static site generation, code splitting, and more.</li></ul><h4>Cons</h4><ul><li><strong>Authentication</strong>: For implementing authentication in your Next.js application, I suggest utilizing Next-Auth, a robust authentication package designed specifically for Next.js projects. Next-Auth offers comprehensive authentication solutions with support for various authentication providers and authentication methods.</li><li><strong>Testing</strong>: When it comes to testing your Next.js application, I recommend leveraging either Playwright or Cypress for end-to-end (E2E) testing. Both Playwright and Cypress are powerful testing frameworks that provide easy-to-use APIs for writing and running automated tests, ensuring the reliability and quality of your application.</li><li><strong>State management</strong>: For managing state in your Next.js application, I suggest considering Zustand or Redux Toolkit. Zustand is a lightweight and fast state management library that offers a simple API for managing state in React applications. Alternatively, Redux Toolkit provides a powerful set of tools and utilities for managing complex state logic, making it well-suited for larger-scale applications. Choose the state management solution that best fits the needs and requirements of your project.</li></ul><h3>Let’s begin by setting up the project.</h3><p>To initiate a new Next.js application:</p><ol><li>Launch your terminal and execute the following command to create a fresh Next.js app:</li></ol><pre>npx create-next-app my-next-app</pre><p>Substitute “my-next-app” with your desired project name.</p><p>2. Move to Your Project Directory:</p><p>Navigate to your project folder:</p><pre>cd my-next-app</pre><p>3. Activate the Development Server:</p><p>Commence the development server by running:</p><pre>npm run dev</pre><p>Your Next.js application is now accessible at <a href="http://localhost:3000/">http://localhost:3000</a>.</p><h4>Understanding the Structure of the Project:</h4><p>Next.js projects adhere to a convention-based structure for better organization. Essential directories include “pages” for routing, “public” for static assets, and “styles” for global styling.</p><h4>Comparison with React:</h4><p>As previously mentioned, there’s often a comparison between Next.js and React. While React is a robust library, it necessitates additional setup for functionalities like server-side rendering. In contrast, Next.js offers these features readily integrated, simplifying the development process.</p><h4>Conclusion:</h4><p>Congratulations on successfully setting up a Next.js project and exploring its integration with React. This guide serves as a foundation for your Next.js journey. As you delve deeper into development, you’ll uncover the extensive capabilities and features that Next.js offers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfdae6f8f1c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Data fetching using Axios with Hooks]]></title>
            <link>https://purtiaggarwal1997.medium.com/react-data-fetching-using-axios-with-hooks-e6400aa44e19?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6400aa44e19</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[axios-react]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 18:18:05 GMT</pubDate>
            <atom:updated>2023-10-01T18:18:05.688Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article we will learn how to server data on our client side(In React using Axios and simple react hooks (i.e., UseEffect and UseState).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FUNmFqJQEwAm9Ujz.jpg" /></figure><p>Before dive into practical part lets first focus on some important defination</p><ol><li><strong>React Hooks:<br></strong>React Hooks introduced in React version 16.8. It is just a replacement for the class based component. React Hooks help us to maintain the react life cycles in function based components .</li></ol><p>In this article we will use two important hooks</p><p><strong>a. UseEffect: </strong>As you understand by its name UseEffect means synchronized with the effects. In simple language useEffect uses to handle the effects of data fetching and any change in DOM. This function run everytime when the DOM renders. we can run this function using the dependency array which have the control for rendening the DOM. UseEffect is an alternative to ComponentDidMount, ComponentDidUpdate, ComponentDidUnmount.</p><blockquote>useEffect(&lt;function&gt;, &lt;dependency&gt;)</blockquote><pre>useEffect(() =&gt; {<br>  //Runs only on the first render<br>}, []);<br><br><br>useEffect(() =&gt; {<br>  //Runs every time when the depency changes.<br>}, [dependecy]);</pre><p><strong>b. UseState:</strong> UseState allow us to save state data in functional component. UseState accept the initial value and return two values :</p><blockquote>Current State</blockquote><blockquote>Value Updating State</blockquote><pre>const [color, setColor] = useState(&quot;&quot;);<br><br>// color =&gt; current state<br>//setColor =&gt; value Updating State<br>//Initial state for color is empty string</pre><p>2. <strong>Axios</strong>: <br>Axios is the library use to make API request from frontend using promise to get the server data. Axios is better in error handle also.</p><h3>Lets Dive into the code</h3><p>Axios is very easy to integrate into the existing React Project.</p><p>First Step: Create a react project using command.</p><pre>npx create-react-app my-react-app</pre><p>Open your project and do start your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*54gb65Jx3prW0P13V77geg.png" /></figure><p>Now we will write simple code for fetching data on rendering the page.</p><p>Second Step: Remove the code in app.js and install the axios library in your project.</p><pre>npm install axios</pre><p>Now first import React , UseEffect and useState from ‘react’ library and axios from axios.</p><pre>import React, { useEffect, useReact } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>...</pre><p>Third Step: let call an API in useEffect and show the data on rendering the component.</p><pre><br><br>// Import necessary modules and libraries<br>import React, { useState, useEffect } from &quot;react&quot;; // Import React and related hooks<br>import axios from &quot;axios&quot;; // Import Axios library for making HTTP requests<br>import &quot;./App.css&quot;; // Import a CSS file (assuming it&#39;s for styling)<br><br>// Define the main functional component named &quot;App&quot;<br>function App() {<br>  // Define a state variable &#39;data&#39; using the &#39;useState&#39; hook, initialized as an empty array<br>  const [data, setData] = useState([]);<br><br>  // Use the &#39;useEffect&#39; hook to perform side effects when the component mounts<br>  useEffect(() =&gt; {<br>   <br>    // Call the &#39;fetchData&#39; function when the component mounts (empty dependency array)<br>    fetchData();<br>  }, []); // Empty dependency array ensures this effect runs only once, when the component mounts<br><br>  // Define an asynchronous function &#39;fetchData&#39;<br>    const fetchData = async () =&gt; {<br>      // Send an HTTP GET request to the specified URL<br>      const response = await axios.get(<br>        &quot;https://fakerestapi.azurewebsites.net/api/v1/Activities&quot;<br>      );<br><br>      // Log the response from the API to the console<br>      console.log(&quot;response&quot;, response);<br><br>      // Update the &#39;data&#39; state with the data from the API response<br>      setData(response.data);<br>    };<br><br>  // Render the component&#39;s content<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      {/* Start of a &lt;div&gt; element with the CSS class &quot;App&quot; for styling */}<br>      &lt;ul&gt;<br>        {/* Start of an unordered list (&lt;ul&gt;) element */}<br>        {data.map((item, index) =&gt; (<br>          // Start of a JavaScript map() function applied to the &#39;data&#39; array<br>          &lt;li key={index}&gt;<br>            {/* Start of a list item (&lt;li&gt;) element. &#39;key&#39; is a unique identifier used for React rendering optimizations. */}<br>            {item.title}<br>            {/* Display the &#39;title&#39; property of each &#39;item&#39; in the list */}<br>          &lt;/li&gt;<br>          // End of the list item (&lt;li&gt;) element<br>        ))}<br>        {/* End of the JavaScript map() function */}<br>      &lt;/ul&gt;<br>      {/* End of the unordered list (&lt;ul&gt;) element */}<br>    &lt;/div&gt;<br>    // End of the &lt;div&gt; element with the CSS class &quot;App&quot;<br>  );<br>}<br><br>// Export the &#39;App&#39; component as the default export<br>export default App;</pre><p>Now just go to the browser and hit <a href="http://localhost:3000/">http://localhost:3000/</a> then the magic happens 😱</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWBwWxPQCjrhO6ngFznDqw.png" /></figure><p>This is how your Data looks like.</p><h3>Conclusion</h3><p>In this blog, we have seen how to use axios in ReactJs using basic hooks.</p><p>Hopefully, this helps you with using APIs in REACTJS.</p><p>In next blog we will see how to do social login in ReactJs.</p><p>Read my other articles</p><ul><li><a href="https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d">Social Media Login Using NodeJs and PassportJs</a></li><li><a href="https://medium.com/jsblend/image-upload-using-nodejs-16b1e804ec92">Image upload using NodeJs</a></li><li><a href="https://medium.com/aeologic/registration-and-login-with-jwt-using-nodejs-expressjs-257ec33baf1f">Registration And Login With JWT Using NodeJs &amp; ExpressJs</a></li><li><a href="https://purtiaggarwal1997.medium.com/how-to-integrate-nodejs-with-reactjs-30d559a142b8">How to integrate NodeJs with ReactJs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6400aa44e19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate NodeJs with ReactJs]]></title>
            <link>https://purtiaggarwal1997.medium.com/how-to-integrate-nodejs-with-reactjs-30d559a142b8?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d559a142b8</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[axios-react]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 11:46:27 GMT</pubDate>
            <atom:updated>2022-08-26T11:46:27.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="NodeJs with ReactJs" src="https://cdn-images-1.medium.com/max/675/1*Ars5vQxTJku6m0CwCG5RIg.jpeg" /></figure><p>The visual feature of the website which can be experienced by the users is the frontend and all the functionalities run in the background in the backend.</p><h4><strong><em>Frontend:</em></strong></h4><blockquote>Frontend is the part of the website which users can interact with . This is also known as <strong>Client-Side</strong>. <strong>ReactJs </strong>is the Javascript library which uses for building user interfaces.</blockquote><h4><strong>Backend:</strong></h4><blockquote>Backend is the part of the website which consists of the server and the database. Server provides the data on request and the Database is used to organize the data.This is also known as <strong>Server-Side</strong>. <strong>NodeJs </strong>is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications.</blockquote><p>So in this article, we are going to learn how to connect <strong>Frontend(ReactJs)</strong> with <strong>Backend(NodeJs)</strong>.</p><h4>Let’s Dive In</h4><h4><strong>Step1: Folder Structure</strong></h4><p>First, create the base folder (<strong>Application</strong>) which consists of the <strong>backend </strong>which contains the backend-related files. and <strong>frontend </strong>which contains the frontend-related files(the frontend folder will be created using the below command).</p><pre>npx create-react-app frontend</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*Zs90ObvfLOgnxjiwIawLWQ.png" /><figcaption>Folder Structure</figcaption></figure><h4>Step2: The Backend</h4><p>First, initialize the backend app by running the command in the terminal.</p><pre>$ npm init -y</pre><p>Now install the required libraries.</p><pre>$ npm i express nodemon</pre><ol><li><strong>Express</strong>: This library is used for a web application framework.</li><li><strong>Nodemon</strong>: This library is used to automatically restart the server when changes are detected.</li></ol><p>Now let’s set up the server</p><pre>const express = require(&quot;express&quot;);</pre><pre>const app = express();</pre><pre>const PORT = 4000 || process.env.PORT;</pre><pre>app.listen(PORT, () =&gt; {<br>console.log(`Server is up ${PORT}`)<br>})</pre><p>The above code is to bind and listen for connections on the specified host and port. We are serving backend at 4000 port.</p><p>Now create test API.</p><pre>...</pre><pre>app.use(&#39;/test-api&#39;,(req, res) =&gt; {<br>   res.send(&quot;YOUR BACKEND IS CONNECTED TO FRONTEND&quot;)<br>});</pre><pre>...</pre><h4>Step3: The Frontend</h4><p>Now come into the frontend folder and start the react-app using command.</p><pre>$ npm start</pre><p>Now your web page looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCDmuds6GqgNlRrGGRX2dA.png" /><figcaption>Webpage</figcaption></figure><p>So we need to change the app.js folder for customizing the webpage.</p><pre>import axios from &#39;axios&#39;;<br>import &#39;./App.css&#39;;</pre><pre>function App() {<br> return (<br>   &lt;div className=&quot;App&quot;&gt;<br>     &lt;h1&gt;Hello World!&lt;/h1&gt;<br>   &lt;/div&gt;<br> );<br>}</pre><pre>export default App;</pre><p>Now Our webpage looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*aGE5LUGlhmfYmKpbz2p6Vw.png" /></figure><p>Let’s call the API in react-app.</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br>import &#39;./App.css&#39;;</pre><pre>function App() {</pre><pre>  const [response, setResponse] = useState(&quot;&quot;);</pre><pre>  useEffect(() =&gt; {<br>    apiCall() // API call on first time when website loads<br>  },[])<br></pre><pre>//This function is used to call the API<br>const apiCall = () =&gt; {<br>  axios.get(&quot;http://localhost:4000/test-api&quot;).then((response) =&gt; {<br>    console.log(&quot;response&quot;, response);<br>    setResponse(response)<br>  })<br> }</pre><pre> return (<br>   &lt;div className=&quot;App&quot;&gt;<br>     &lt;h1&gt;Hello World!&lt;/h1&gt;<br>     &lt;h2&gt;{response? response: &quot;&quot;}&lt;/h2&gt;<br>   &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>But now we will face CORS Errors because we are calling API of the different PORT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEWfF0POmWIKlOHk7V7UpQ.png" /><figcaption>CORS Errors.</figcaption></figure><p>To solve this issue we need to use library cors in the backend.</p><p>First, install cors.</p><pre>$ npm install cors</pre><p>Now we need to do a small part of the code</p><pre>...<br>const cors = require(&quot;cors&quot;);</pre><pre>...</pre><pre>app.use(cors);</pre><pre>...</pre><p>Using this code we can resolve the cors issue and we are successfully called API. So Now our webpage looks like as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2MpwPDSjZPm2CXRZUPGxw.png" /><figcaption>Webpage</figcaption></figure><h3>Conclusion</h3><p>In this blog, we have seen how to integrate the NodeJs with ReactJs, so we can save out website in database and connect to the server. We have learned how to handle the <strong>CORS </strong>errors so we can run our backend server with the frontend.</p><p>Hopefully, this helps you with using APIs in REACTJS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d559a142b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social Media Login Using NodeJs and PassportJs]]></title>
            <link>https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9b58cc359d</guid>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[passport]]></category>
            <category><![CDATA[facebook]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 14:20:18 GMT</pubDate>
            <atom:updated>2021-06-17T14:21:46.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnsmT69Ty6Dnm0UHj7aELw.png" /></figure><p>Social media login is a very easy step for registering for the new apps. This allows end-users for using their existing information from social network platforms like <strong>Facebook</strong>, <strong>Google</strong>, <strong>Twitter</strong>,<strong> </strong>and <strong>LinkedIn. </strong>The user can use these websites instead of creating new accounts. This is just one step process for getting registered into the new app. This also reduces the verification step for the new users.</p><p>In this article, we will see how to register using Google and Facebook accounts using <strong>NodeJs </strong>and <strong>PassportJs</strong>.</p><blockquote><strong>PassportJs</strong> is the library that provides authentication strategies for different social media accounts. This use as middleware in NodeJs projects.</blockquote><h3>Let’s Dive In</h3><h4><strong>Step 1: Project Structure</strong></h4><p>First, create the base folder (authentication-project) which contains all the project-related files and directories.</p><p>Our project will have the server.js which has the server code, the .env file which has all environmental variables, passport-setup.js will have the code setting up different strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*VFPn5-7FPeWrWZBrJkVqXA.png" /><figcaption>Directory SetUp</figcaption></figure><h3>Step 2: Initialize App</h3><p>Now our next step to initialize our project by running the below command in the terminal.</p><pre>$ npm init -y</pre><p>Now we will install the required dependencies.</p><pre>$ npm i express dotenv nodemon ejs passport passport-facebook passport-google-oauth2 cookie-session</pre><ol><li><strong>Express: </strong>Express is used as a web application framework.</li><li><strong>Dotenv: </strong>Dotenv module has zero dependencies that load environmental variables.</li><li><strong>Nodemon: </strong>This tool is used to automatically restart the server when the change detected.</li><li><strong>Ejs: </strong>Ejs is a templating engine.</li><li><strong>Passport: </strong>Passport is authentication middleware for the NodeJs.</li><li><strong>Passport-facebook: </strong>Passport-facebook is the passport strategy for authenticating Facebook.</li><li><strong>Passport-google-oauth2: </strong>Passport-google-oauth2 is the passport sategy for authenticating google.</li><li><strong>Cookie-session: </strong>Cookies-session is a middleware module the stores our data on the client side.</li></ol><p>After installing all the modules this is how our package.json looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*toirznvAZHuCPpTyIRsSlw.png" /><figcaption>Package.json</figcaption></figure><h3>Step 3: Configure Strategies</h3><p>For configuring different media platforms we need APP_ID and APP_SECRET for each media strategy. The APP_ID and APP_SECRET can be obtained by creating the app in the developer link.</p><p>The developer app links for the different media platforms.</p><ol><li><strong>Facebook</strong>: <a href="https://developers.facebook.com/">https://developers.facebook.com/</a></li><li><strong>Google</strong>: <a href="https://console.cloud.google.com/apis/dashboard">https://console.cloud.google.com/apis/dashboard</a></li><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/developers/">https://www.linkedin.com/developers/</a></li><li><strong>Twitter</strong>: <a href="https://developer.twitter.com/en">https://developer.twitter.com/en</a></li></ol><p>In this article, we will configure Google APP_ID and APP_SECRET.</p><p>For Configure Google APP_ID and APP_SECRET Follow the below steps:</p><ol><li>Go to the Google console developer link <a href="https://console.cloud.google.com/apis/dashboard">https://console.cloud.google.com/apis/dashboard</a> and log in with your Google account.</li><li>Once you registered then go to the project dropdown and select the existing project or create the new project.</li></ol><p>This window will be shown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9Uo575rV3QXTr9mujmfHw.png" /></figure><p>3. Now go to the credentials under APIs &amp; Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDALuHxl0Ew6-LmsTaKrvg.png" /></figure><p>4. Now select the create credentials drop list and choose OAuth Client ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBsVVUlSpCp0vgWIU6sjIA.png" /></figure><p>5. Now choose Web Application under the Application type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqDkXGfng_NC7fC2ZXl8DA.png" /></figure><p>6. Now give the authorized URL under the Authorized redirect URLs. like we are giving <a href="http://localhost:3000/google/callback">http://localhost:3000/google/callback</a> and the last step is to click create button.</p><p>Now the pop up comes on the screen which has the APP_ID and APP_SECRET</p><p>Similarly, you can get APP_ID and APP_SECRET for all the media platforms.</p><p>Now we set up <strong>passport-setup.js. </strong>In this file, we configure all the social media strategies. These strategies use to authenticate the user and handle the callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480fcb2dcdf52a722421bfce769a1bd7/href">https://medium.com/media/480fcb2dcdf52a722421bfce769a1bd7/href</a></iframe><p>Now we write the server code in the server.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0805622583a34c5159b938f3712d78c6/href">https://medium.com/media/0805622583a34c5159b938f3712d78c6/href</a></iframe><p>Now our last step is to create the frontend.</p><h3>Step 4: Create Frontend</h3><p>We create the templates using the ejs template engine. we create two pages index.ejs and the profile.ejs under the views/pages/ directories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6063197702b17723e36740e9eeb4507/href">https://medium.com/media/d6063197702b17723e36740e9eeb4507/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb5902183770c1f3d2044cda99f85216/href">https://medium.com/media/cb5902183770c1f3d2044cda99f85216/href</a></iframe><p>Our App is completed. Now we can test.</p><h3>Step 5: Test the work</h3><p>Start up the server and open the project URL on the browser.</p><p>The project URL is <a href="http://localhost:3000/"><strong>http://localhost:3000</strong></a></p><p>Hit this URL on the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUsieAhRu8_VWPnqJebuoQ.png" /><figcaption>Index page</figcaption></figure><p>With on click of the google button, the URL redirects and displays this signing dialog box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l52TjRB2GZ__wZxV9MiDGQ.png" /></figure><p>After choosing the email. The URL will be redirected to a Profile page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iACn6mpvMB2yjymFNkQ67Q.png" /><figcaption>Profile Page</figcaption></figure><p>Similarly, we can test all the media platforms.</p><h3>Conclusion</h3><p>In this article, I explained how to authenticate different social media platforms to the App. We see how to configure different passport strategies for a different social media account and we also look at how to get client_id and the secret_id for configuring the strategies.</p><p>You can find the code <a href="https://github.com/jsblend/google-facebook-authentication-with-passportJs.git">[here]</a></p><p>Read my other articles</p><ul><li><a href="https://medium.com/jsblend/how-to-serve-static-resource-with-node-js-e86aa85b81c3">How to Serve Static Resource With Node.js</a></li><li><a href="https://medium.com/jsblend/how-to-send-emails-with-templates-using-nodejs-176b72c1406d">How to Send Emails With Templates using NodeJs</a></li><li><a href="https://medium.com/jsblend/image-upload-using-nodejs-16b1e804ec92">Image upload using NodeJs</a></li><li><a href="https://medium.com/jsblend/crud-operation-c5ba129d72df">Crud Operation</a></li><li><a href="https://medium.com/aeologic/registration-and-login-with-jwt-using-nodejs-expressjs-257ec33baf1f">Registration And Login With JWT Using NodeJs &amp; ExpressJs</a></li><li><a href="https://medium.com/aeologic/getting-started-with-nodejs-10e6180aea96">Getting started with NodeJs</a></li></ul><p>If you like this article, give it a clap 👏 ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9b58cc359d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jsblend/social-media-login-using-nodejs-and-passportjs-be9b58cc359d">Social Media Login Using NodeJs and PassportJs</a> was originally published in <a href="https://medium.com/jsblend">jsblend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Emails With Templates using NodeJs]]></title>
            <link>https://medium.com/jsblend/how-to-send-emails-with-templates-using-nodejs-176b72c1406d?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/176b72c1406d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[template]]></category>
            <category><![CDATA[handlebarsjs]]></category>
            <category><![CDATA[nodemailer]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 13:49:54 GMT</pubDate>
            <atom:updated>2021-06-03T13:49:54.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZB2gZq1_luXaiq-DY7KyA.png" /></figure><p>In this technology world, email is the most tool which you to reach your users. This article will give you brief how-to send emails with attractive templates using the server NodeJs. We are going to use the nodemailer library for sending mail. <strong>Nodemailer </strong>is a library that allows us to send emails through the mails. We can send emails when we want to communicate with the client-side users or notify developers when something went wrong.</p><blockquote><strong>Nodemailer </strong>is the module for NodeJs application which allow sending emails as easy as sending cake.</blockquote><p>We are going to use handlebars for designing our emails.</p><blockquote><strong>Handlebar </strong>is a template engine to make writing html code easier.</blockquote><h3>Let’s do it practically</h3><h3>Step:1 Project Structue</h3><p>We will make the <strong>index.js</strong> file which contains the server code of the project inside the src directory. The src directories also have an <strong>image </strong>directory and the <strong>templates </strong>directory. The image directory will have static images whereas the templates directory will have templates that we will send through the emails, <strong>partials directory </strong>has snippets that can be shared between pages, such as header and footer, and <strong>views </strong>directory contain the pages. Later on, 3 more directories will be added named <strong>node_module, package-lock.json, </strong>and <strong>package.json</strong> which have the data of installed modules.</p><p><strong>LICENSE</strong>, .<strong>gitignore, </strong>and <strong>README.md</strong> are the git files.</p><blockquote><strong>Check out my </strong><a href="https://medium.com/@purtiaggarwal1997/57b90b928b9"><strong>previous blog</strong></a><strong> on how to setup a project from scratch.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYbqI4LRjCr_91q49-uSig.png" /><figcaption>Directory Structure</figcaption></figure><h3>Step:2 Installing the Modules</h3><p>We need to set up the <strong>package.json</strong> file by running the below command in the terminal inside the application directory:</p><pre>$ npm init -y</pre><blockquote><strong>npm init -y command </strong>will take default configuration like description, name and other config.</blockquote><blockquote>If you want to provide custom configuration use <strong>npm init </strong>and it will ask you to enter all the details manually.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jLyOiKnXwBDb7UG2.png" /><figcaption>Bash File</figcaption></figure><p>Now Install the required Modules</p><pre>$ npm i express nodemailer nodemailer-express-handlebars</pre><ol><li><strong>Express</strong>: Express is used as a web application framework.</li><li><strong>Nodemailer-express-handlebars</strong>: Nodemailer-express-handlebars<strong> </strong>is a plugin for nodemailer for the use of express-handlebars.</li><li><strong>Nodemailer: </strong>Nodemailer is the module for the NodeJs application that allows sending emails as easily as sending a cake.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlwycGuABu-ekC_IZfe90w.png" /><figcaption>Package.json</figcaption></figure><h3><strong>Step:3 Setup Server File</strong></h3><p>Let’s start with the server file, Server file is the main file of our project that is index.js. The index.js file has the code for setting the server. Once the server up and running, the user can able to hit API’s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e426c3b18895473f2556890ae12bfcad/href">https://medium.com/media/e426c3b18895473f2556890ae12bfcad/href</a></iframe><p>The <strong>app</strong>.<strong>listen</strong>() function used to bind and listen to the connection on the specified host and port.</p><h3>Step:4 Config Gmail Account</h3><p>For sending the email we are using a Gmail account which means we are using Gmail as our transport service. So, now our next step is to tell nodemailer to login into our account and send emails on our behalf. This can be done by using <strong>nodemailer.transport() </strong>function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feadab807fbe99bc91ec9c1466ee7609/href">https://medium.com/media/feadab807fbe99bc91ec9c1466ee7609/href</a></iframe><p>Next, we need to configure the data which we have to use for sending mail inside the sendMail function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2029cadad8ecbf6a5fe97df7ddd5417b/href">https://medium.com/media/2029cadad8ecbf6a5fe97df7ddd5417b/href</a></iframe><p>These are important options for sending an email with a designing template.</p><ol><li><strong>Form: </strong>Here we have to mention the sender’s email id.</li><li><strong>To: </strong>Here we give the receiver&#39;s email id.</li><li><strong>Subject: </strong>Here we give the subject of the email.</li><li><strong>Template: </strong>Here we give the template name which template we want to send through the email.</li><li><strong>Attachment: </strong>Here we mention the fileName and the path of that file which we want to send as an attachment.</li></ol><h3>Step:5 Create template</h3><p>Now we create an email template but first, we have to allow nodemail to compile the handlebars. For this, we have a middleware transport.use()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/879a33d48d0035413b5a4482dae22a46/href">https://medium.com/media/879a33d48d0035413b5a4482dae22a46/href</a></iframe><p>Now, we moving ahead for creating a template. First, we code for the partials. Partials have a small part of code that can be used in the template pages.</p><p>First, we create header.handlebars</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb41a222f81fb8cb9579db3f7093952/href">https://medium.com/media/1bb41a222f81fb8cb9579db3f7093952/href</a></iframe><p>Now, we code for footer.handlebars</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8849461fd376dcb5ef8039a909e7082/href">https://medium.com/media/a8849461fd376dcb5ef8039a909e7082/href</a></iframe><p>The last step is to create a page for the template inside ‘templates/views/index.handlebars’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e87874c4fb653f07ad96478e91bbc471/href">https://medium.com/media/e87874c4fb653f07ad96478e91bbc471/href</a></iframe><h3>Step:6 Hit API</h3><p>Our last step is to create an API for sending emails.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b062663a7cc664a669b42712fd99e4d9/href">https://medium.com/media/b062663a7cc664a669b42712fd99e4d9/href</a></iframe><p>Now it’s time to test our work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bioKDqIAosPivSMA4elKg.png" /><figcaption>Result of API</figcaption></figure><h3>Conclusion</h3><p>In this blog, we have seen how to send emails from the server and we used the Gmail service to send the email. We also learned how to use handlebars to send templates. To send an email we use the nodemailer module. <strong>Nodemailer</strong> helps us to send emails easily. <strong>Handlebars </strong>are the view engine for the code HTML easily on the server-side.</p><p>Hopefully, this helps you with sending emails using NodeJs.</p><p>You can find the above code <a href="https://github.com/jsblend/email-template-using-nodejs.git">[here]</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176b72c1406d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jsblend/how-to-send-emails-with-templates-using-nodejs-176b72c1406d">How to Send Emails With Templates using NodeJs</a> was originally published in <a href="https://medium.com/jsblend">jsblend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image upload using NodeJs]]></title>
            <link>https://medium.com/jsblend/image-upload-using-nodejs-16b1e804ec92?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b1e804ec92</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[multiple-image-upload]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Mon, 24 May 2021 17:03:38 GMT</pubDate>
            <atom:updated>2021-05-24T17:03:38.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0374IVbNNTIn6qgjaYXpQ.png" /></figure><p>Nowadays, the most common feature of any website is uploading an image as an input from the client-side and storing it in the database. That’s what we implementing here.</p><p>For this, we need the <strong>multer</strong>, Multer is the<strong> </strong>library that allows your application to easily support the file upload.</p><blockquote><strong>Multer</strong> is a middleware in the NodeJs which is primarily used for uploading the files</blockquote><h4>Let’s start to build the API</h4><h3>Step-1: Project Structure</h3><p>First, we will create the base directory which contains all project-related directories. Now create the src folder which contains the server-side specific file. So, the <strong>router</strong>, <strong>controller</strong>, <strong>DB, </strong>and <strong>models </strong>all are inside the src directory.</p><blockquote><strong>Check out </strong><a href="https://medium.com/aeologic/getting-started-with-nodejs-10e6180aea96?source=friends_link&amp;sk=5b80c4227af21191c2d033f00b57f3d9"><strong>my previous</strong></a><strong> blog on how to setup a project from scratch.</strong></blockquote><p>Inside the src folder create new folders — <strong>controller</strong>, <strong>DB</strong>, <strong>middleware</strong>, <strong>models </strong>&amp; <strong>router</strong>.</p><p>Now the project structure will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_2oea3-PU9zt9e66rcgoWg.png" /><figcaption>Directory Steup</figcaption></figure><h3>Step-2: Initialize Project</h3><p>We need to set up the <strong>package.json</strong> file by running the below command in the terminal inside the application directory:</p><pre>$ npm init -y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rnnNnZrFnQOih7hL.png" /><figcaption>Git Bash</figcaption></figure><blockquote><strong>npm init -y </strong>command will take default configuration like description, name and other config.</blockquote><blockquote>If you want to provide custom configuration use <strong>npm init </strong>and it will ask you to enter all the details manually.</blockquote><h3>Step-3: Installation of modules</h3><pre>$ npm i express multer body-parser mongodb mongoose dotenv</pre><ol><li><strong>Express:</strong> Express is used as a web application framework.</li><li><strong>Mongoose: </strong>The mongoose is used to connect the database with our project.</li><li><strong>MongoDB: </strong>MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.</li><li><strong>Body-parser: </strong>Extract the entire body portion of an incoming request stream and exposes it on req.body.</li><li><strong>Multer</strong>: Multer is a middleware used for the file upload.</li></ol><h3>Step-4: Configure the model</h3><p>First, we create the directory ./src/db/mongoose.js</p><p>Here we create a connection with the mongoose database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f87edf3f8306d3f7e8fb8a113637c9/href">https://medium.com/media/e8f87edf3f8306d3f7e8fb8a113637c9/href</a></iframe><p>Above 127.0.0.1:27017 is the localhost server and the image is the database name and mongoose.connection() is a function to connect the database.</p><h3>Step-5: Create the model</h3><p>In the model, we define the structure of the data.</p><p>We have structured the database inside the mongoose.Schema(). Our User model has one field image.</p><p>So, now create ./src/models/image.js &amp; import the required modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eb79e5582b9585eca113f2504e081c5/href">https://medium.com/media/2eb79e5582b9585eca113f2504e081c5/href</a></iframe><h3>Step-6: Create the service</h3><p>Now, we are creating a separate class for the image upload which has a single image upload function and multiple image upload functions.</p><p>First, create the directory ./src/service/image.js up to the project root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38cf9fb12670d360890c5d23693bd85e/href">https://medium.com/media/38cf9fb12670d360890c5d23693bd85e/href</a></iframe><h3>Single Image Upload</h3><p>Now, we create and test the upload image API.</p><h3>Step-7: Create the controller</h3><p>Now we are going to create a controller which helps in getting the requested data from the model.</p><p>First, create the directory ./src/controller/userController up to the project root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97b1b21f85fb4adf0e8ff1c195150d48/href">https://medium.com/media/97b1b21f85fb4adf0e8ff1c195150d48/href</a></iframe><h3>Step-8: Create the router</h3><p>First, we create the file ./src/router/userRouter.js with the project root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6458c76f4a8635b0aa643fc5d75b1b25/href">https://medium.com/media/6458c76f4a8635b0aa643fc5d75b1b25/href</a></iframe><p>The above multer limit is used for limiting the size of the image this API will accepting 1MB images and dest provides the location where the uploaded image should be stored.</p><p>Multer is then added as middleware for the specific endpoint that should allow for file uploads. The route below is expecting a single image upload on sending the request.</p><h3>Step-9: Create the index.js</h3><p>Index.js is the main file of the project</p><p>Here, we going to import all the files of this project because the index handles all the startups and functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/448cdf76848ee47b585a467a404e802c/href">https://medium.com/media/448cdf76848ee47b585a467a404e802c/href</a></iframe><h3>Step-10: Test your work</h3><p>Here we are going to test our work.</p><p>First, we have to on the mongoose server. For this, we have to run the command in the terminal.</p><pre>$ c:/Users/mongodb/bin/mongod.exe --dbpath c:/Users/mongodb-data</pre><p>Now start the server then test API in the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*90KGjHIL0cSGTJI2.png" /><figcaption>Result for a single image upload.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*Xq7BXDvcyC53BbdL.png" /><figcaption>Database for a single image upload.</figcaption></figure><h3>Multiple Image Upload</h3><p>Now, we create and test the multiple-image upload API.</p><p>As we already made the service function above in the article.</p><h3>Step-11: Update the controller</h3><p>We are creating a controller for multiple images upload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b5fa1e9966190a2cdfc5bed98455285/href">https://medium.com/media/5b5fa1e9966190a2cdfc5bed98455285/href</a></iframe><h3>Step-12: Update the router</h3><p>Now, route the request for multiple image uploads.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac2322f307aabdad1bf1dd0df355709b/href">https://medium.com/media/ac2322f307aabdad1bf1dd0df355709b/href</a></iframe><h3>Step-13: Test Work</h3><p>Now start the server then test API in the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*XEdm71j5ZmQ96lpl.png" /><figcaption>Result for multiple images upload.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*I_jPhhKguvs4P1b7.png" /><figcaption>Database for multiple images upload.</figcaption></figure><h3>Summary</h3><p>In this blog, we learned about single and multiple image uploads. Multer library is used to handle the different file uploads. It is used as a middleware for express and nodeJs to handle the multipart/form-data when the user uploads files. Here we make a class having a single image upload and multiple image upload functions. These functions are called in the controller and then the image path stored in the database.</p><p>In my next blog, we will see how to send and receive the mail in NodeJs.</p><p>Hopefully, this article will help you with image upload using NodeJs.</p><p>You can find the above code [<a href="https://github.com/jsblend/image-upload-nodejs-with-express-and-multer.git">here</a>].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b1e804ec92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jsblend/image-upload-using-nodejs-16b1e804ec92">Image upload using NodeJs</a> was originally published in <a href="https://medium.com/jsblend">jsblend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Serve Static Resource With Node.js]]></title>
            <link>https://medium.com/jsblend/how-to-serve-static-resource-with-node-js-e86aa85b81c3?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86aa85b81c3</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[static-file]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Thu, 20 May 2021 14:51:56 GMT</pubDate>
            <atom:updated>2021-05-20T16:36:28.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aY0FkKkgOpC0j42kYw0cPw.png" /></figure><p>The static resource is that files can be downloaded from the server. It is very easy to serve the static resource.</p><p>The Express middleware can serve the static files to the server. The static files include HTML, javascript, CSS, images, and many more.</p><p>Nowadays a website has many static files. It has different fonts, styles scripts files. All these files send via the server so they can be loaded easily.</p><p>With Express we don’t have to manually send each file. We can send the entire static directory simultaneously.</p><p>For the absolute path, we have to install the path module.</p><h4><strong>Let’s do it practically</strong></h4><h3><strong>Step-1: Project structure</strong></h3><p>We will make the <strong>index.js</strong> file which contains the server code of the project. next, we create the<strong> .env</strong> file which has all the environment variables. Later on, 3 more directories will be added named <strong>node_module, package-lock.json </strong>and <strong>package.json</strong> which have the data of installed modules. And the last directory is the <strong>public</strong> folder which we will discuss later on.</p><p><strong>LICENSE</strong>, .<strong>gitignore, </strong>and <strong>README.md</strong> are the git files.</p><blockquote><strong>Check out my </strong><a href="https://medium.com/@purtiaggarwal1997/57b90b928b9"><strong>previous blog</strong></a><strong> on how to setup a project from scratch.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqfOkNETg5n3FoyHNjieoA.png" /></figure><h3><strong>Step-2: Setting up the modules</strong></h3><p>We need to set up the <strong>package.json</strong> file by running the below command in the terminal inside the application directory:</p><pre>$ npm init -y</pre><blockquote><strong>npm init -y command </strong>will take default configuration like description, name and other config.</blockquote><blockquote>If you want to provide custom configuration use <strong>npm init </strong>and it will ask you to enter all the details manually.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bJMENtnncT3ImYj7f82fBA.png" /></figure><p>Now Install the required Modules</p><pre>$ npm i express path dotenv</pre><ol><li><strong>Express</strong>: Express is used as a web application framework.</li><li><strong>Path</strong>: Path provides the absolute path.</li><li><strong>Dotenv: </strong>Dotenv helps to configure the environment variables.</li></ol><h3><strong>Step-3: Serve the static files</strong></h3><p>By default, Express does not allow the serving of static files.</p><p>We need to enable it by using the middleware.</p><pre>app.use(express.static(&#39;public&#39;))</pre><blockquote><strong>express.static()</strong> create the root route. So, now all the static files consider the public directory as root route.</blockquote><blockquote>Express itself looks for the static files. Therefore, the name of static files doesn’t go in the URL.</blockquote><p>The public directory contains those files which are exposed to the server if the file is not in the public directory then that file will not be loaded to the server.</p><blockquote><strong>dotenv </strong>is helps to get environment variables. Dotenv configures the environment variables from the <strong>.env </strong>file to process.env.</blockquote><blockquote><strong>Environmental variable </strong>An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg0Wfp0StHtnRp2vX_p2bQ.png" /><figcaption>server file index.js</figcaption></figure><blockquote><strong>Path </strong>module provides the way of working with directories and files.</blockquote><blockquote><strong>path.join() </strong>helps to join the one specified path to the other path.</blockquote><blockquote>The first parameter <strong>__dirname</strong> gives the path of the current directory and the second one gives the public directory path.</blockquote><p>We can serve the static images and js files in a public directory.</p><p>So create a directory named <strong>images </strong>and save an image named <strong>background.jpeg. </strong>Same for the javascript file creates a directory named <strong>js</strong> and save a file name <strong>myJsFile.js.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*539ckpS8o9AtR73EcCsvZA.png" /></figure><p>This is how your HTML file looks like. The HTML file renders the image under the path “/images/background.jpeg” and js file “/js/myJsFile.js”.</p><h3><strong>Step-4: Test your work</strong></h3><p>The last step of the project is to test your work.</p><p>Start the server up and check your work on chrome.</p><p>The file will server on URL:</p><blockquote><a href="http://localhost:3000/"><strong><em>http://localhost:3000</em></strong></a><strong><em> </em></strong><em>renders Html file.</em></blockquote><blockquote><a href="http://localhost:3000/"><strong><em>http://localhost:3000</em></strong></a><strong>/images/background </strong>render image.</blockquote><blockquote><a href="http://localhost:3000/"><strong><em>http://localhost:3000</em></strong></a><strong>/js/myJsFile.js </strong>render js file.</blockquote><h3>Conclusion</h3><p>In this article, I explained how to serve the static files with NodeJs and the use of dotenv so that we can use environment variables. Environment variables are the dynamic values that can be changed from processor to processor.</p><p>I hope this article helps you with the serving static file in NodeJs.</p><p><em>You can find the project on GitHub </em><a href="https://github.com/jsblend/how-to-serve-static--resource-with-nodejs.git"><em>[here]</em></a></p><p>Read my other articles:</p><ul><li><a href="https://medium.com/jsblend/crud-operation-c5ba129d72df">Crud Operation</a></li><li><a href="https://link.medium.com/KkiO97ENpgb">Getting started with NodeJs</a></li><li><a href="https://link.medium.com/ISFwo9HNpgb">Registration And Login With JWT Using NodeJs &amp; ExpressJs</a></li></ul><p>If you like this article give a clap 👏 ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86aa85b81c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jsblend/how-to-serve-static-resource-with-node-js-e86aa85b81c3">How to Serve Static Resource With Node.js</a> was originally published in <a href="https://medium.com/jsblend">jsblend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crud Operation]]></title>
            <link>https://medium.com/jsblend/crud-operation-c5ba129d72df?source=rss-2cd25a483a9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ba129d72df</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[crud-operations]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Wed, 12 May 2021 17:56:27 GMT</pubDate>
            <atom:updated>2021-05-12T19:21:17.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mhcx64sPP5eyTOr-UZbnQ.png" /></figure><h3>NodeJs CRUD Operation Using MongoDB And Mongoose</h3><p>REST API stands for “ <strong>Representational State Transfer Application Programming Interface</strong>. ” API uses the URLs to address the resources.API work like a mediator helps us to talk between the server and the client-side. API created on the server. REST decides how the API looks like. We can send a request through URL and get the data in return which is called the response.</p><p><strong>CRUD </strong>operation means the basic <strong>Create Read Update Delete</strong> operation. Here, we are going to learn the crud operation of MongoDB.</p><p><strong>Let’s start creating the CRUD API’s</strong></p><h3><strong>Step-1: Set up directories</strong></h3><p>First, create the base folder(application) which contains all project-related directories. Now create the src folder which contains the server-side specific file.</p><blockquote><strong>Check out my previous blog for learn to set up project from scratch.</strong></blockquote><p>So the basic project setup will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyySqOT0oJkdmLucWA8oog.png" /><figcaption>Directory Setup</figcaption></figure><h3>Step-2: Initialize App</h3><p>First, for initializing the app run the below command in the terminal.</p><pre>$ npm init -y</pre><p>Second, Install the required dependencies.</p><pre>$ npm install express mongoose validator body-parser nodemon</pre><ol><li><strong>Express:</strong> Express is used as a web application framework.</li><li><strong>Mongoose: </strong>The mongoose is used to connect the database with our project.</li><li><strong>Validator: </strong>This library validates and sanitizes strings only.</li><li><strong>Body-parser: </strong>Extract the entire body portion of an incoming request stream and exposes it on req.body.</li><li><strong>Nodemon: </strong>This tool is used to automatically restart the server when the change detected.</li></ol><p>So this is how your package.json will look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6n7oqIhOqmKOoSOtq0m1g.png" /><figcaption>package.json</figcaption></figure><h3><strong>Step-3: Configure the Database</strong></h3><p>Mongoose makes it easier to model our data. This includes data sanitization, data validation, and more. <strong>Mongoose </strong>has a connection function mongoose.connect() which we are using for connecting our application project with MongoDB.</p><p>First, we have to create the file ./src/db/mongoose.js under the root project.</p><p>Now we have to require the mongoose module and then declare the <strong>MongoDB URL</strong> for the connection</p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><pre>MONGO_URL = &#39;mongodb://127.0.0.1:27017/app&#39;</pre><pre>mongoose.connect(MONGO_URL, () =&gt; {<br>     console.log(&quot;Database Connected!&quot;)<br>}</pre><h3><strong>Step-3: Modelling the Data</strong></h3><p>The main feature of Mongoose is to model our data. In one application you can create different models for different types of collections of data. We can create numerous models for our application.</p><p>First, create ./src/models/user.js &amp; import the required modules.</p><pre>const mongoose = require(&#39;mongoose&#39;)<br>const validator = require(&#39;validator&#39;)</pre><pre>// Here we defining our Schema(Structure of our collection).</pre><pre>const userSchema = mongoose.Schema({<br>       name: {<br>          type: String,<br>          trim: true,<br>          required: true,<br>        },<br>        email: {<br>          type: String,         <br>          required: true,<br>          trim: true,<br>          lowercase: true,<br>          validate(value) {<br>             if (!validator.isEmail(value)) {<br>                 throw new Error(&#39;Email is invalid&#39;)<br>             }<br>          }<br>       },<br>       phone_number: {<br>           type: Number,<br>           required: true,<br>        },<br>       age: {<br>           type: Number,<br>           required: true<br>        }<br>const User = mongoose.model(&#39;User&#39;, userSchema)</pre><pre>module.exports = User</pre><h3><strong>Create API</strong></h3><p>For creating the REST API <strong>POST HTTP</strong> method is used. The URL structure is<strong><em> /endpoint</em></strong>. If we wanted to create a <strong><em>user</em></strong>, it would be POST <strong><em>/create-user</em></strong>. Here ‘create-user’ is an endpoint.</p><p>For this first create the route file ./ src/router/user.js up to the root project.</p><p>Now we route the request in the router file.</p><pre>$ npm i express</pre><pre>const express = require(&#39;express&#39;)</pre><pre>const router = express.Router()</pre><pre>//Create User<br>router.post(&#39;/create-user&#39;, AuthController.createUser)<br>...</pre><p>For controlling the logic create the controller file ./ src/controller/user.js.</p><pre>const UserModel = require(&#39;../models/user.js&#39;);</pre><pre>class AuthController {<br>    static createUser = async (req, res) =&gt; {<br>         try {<br>             const user = new User(req.body);<br>             await user.save()<br>             if(user) {<br>                       res.status(200).send({<br>                                             status: 200,<br>                                             user<br>                                           })</pre><pre>                      }</pre><pre>            } catch (error) {<br>                 res.status(500).send({<br>                                       status: 500,<br>                                       message: error.message</pre><pre>                                      })<br>              }</pre><pre>   }</pre><pre>}</pre><pre>module.exports = AuthController;</pre><p><strong>Start the server</strong></p><p>Now we are going to create the main file of our project (index.js).</p><p>We have to require all files in index.js because it handles our application startups and all other functions.</p><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const userRouter = require(&#39;./router/userRouter&#39;)<br>require(&#39;./db/mongoose&#39;)const app = express()<br> <br>app.use(bodyParser.json())<br>app.use(bodyParser.urlencoded({extended: true})</pre><pre>app.use(userRouter)</pre><pre>const port = process.env.PORT || 3000;</pre><pre>app.listen(port, ()=&gt; {<br>    console.log(&#39;Server is up to &#39;+ port)<br>})</pre><p><strong>Test API</strong></p><p>We have to send the data in the JSON form through the JSON body of the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*X7JblTUEjLIU0ziQ6hVWHQ.png" /><figcaption>Send API Data.</figcaption></figure><p>If your code correctly then you will get the status 200 OK and the result as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*M22JWfoL0qOfyJqSxgTIUg.png" /><figcaption>Response of API</figcaption></figure><h3>Read API</h3><p>For creating the REST API <strong>GET HTTP</strong> method is used. The URL structure is<strong><em> /endpoint</em></strong>. If we wanted to get all <strong><em>users</em></strong>, it would be GET <strong><em>/read-users</em></strong>. Here ‘read-users’ is an endpoint.</p><p>For this first create the route file ./ src/router/user.js up to the root project.</p><p>Now we route the request in the router file.</p><pre>$ npm i express</pre><pre>const express = require(&#39;express&#39;)</pre><pre>const router = express.Router()</pre><pre>//Create User<br>router.get(&#39;/read-user/:id&#39;, AuthController.getAllUsers)<br>...</pre><p>For controlling the logic create the controller file ./ src/controller/user.js.</p><pre>...</pre><pre>static getAllUser = async (req, res) =&gt; {</pre><pre>       const _id = req.params.id // retrieve the id provided <br>       User.findById(_id).then((user) =&gt; {<br>       if (!user) {<br>             return res.status(404).send({<br>                                         message: &quot;User Not Found&quot;<br>                                        })<br>       } <br>        res.send(user)<br>     }).catch((e) =&gt; {<br>         res.status(500).send()<br>     })<br> });<br>}</pre><p><strong>Start the server</strong></p><p>Start the server the same as we started on Create API</p><p><strong>Test API</strong></p><p>If your code correctly then you will get the status 200 OK and the result as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*M45tZ_mEv3wSyh06cWd3ng.png" /><figcaption>Response Read API</figcaption></figure><h3>Update API</h3><p>For creating the REST API <strong>PATCH HTTP</strong> method is used. The URL structure is<strong><em> /endpoint</em></strong>. If we wanted to get all <strong><em>users</em></strong>, it would be PATCH <strong><em>/update-user/:id</em></strong>.</p><p>Now we route the request in the router file.</p><pre>...</pre><pre>//Create User<br>router.patch(&#39;/update-user/:id&#39;, AuthController.updateUsers)<br>...</pre><p>For controlling the logic create the controller file ./ src/controller/user.js.</p><pre>...</pre><pre>static updateUser = async (req, res) =&gt; {</pre><pre>try {<br>        const user = await User.findByIdAndUpdate(req.params.id,<br>                                                  req.body, <br>                                   {new: true, runValidators: true}) <br> <br>       if (!user) {<br>         return res.status(404).send({<br>                                     message: &quot;User not found&quot;<br>                                    })<br>       }else {<br>          res.send(user)<br>       } <br>       <br>   } catch (e) {<br>     res.status(400).send(e)<br>   }<br>}<br>...</pre><p><strong>Start the server</strong></p><p>Start the server the same as we started on Create API</p><p><strong>Test API</strong></p><p>We have to send the data in the JSON form through the JSON body of the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*xbv6zHUbTAEfzlfbdFC00g.png" /><figcaption>Send Request Data</figcaption></figure><p>If your code correctly then you will get the status 200 OK and the result as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*8__U54LRNRYZuUF74Nf8yg.png" /><figcaption>Result of Update Data</figcaption></figure><h3>Delete API</h3><p>For creating the REST API <strong>DELETE HTTP</strong> method is used. The URL structure is<strong><em> /endpoint</em></strong>. If we wanted to get all <strong><em>users</em></strong>, it would be DELETE <strong><em>/delete-user/:id</em></strong>.</p><p>Now we route the request in the router file.</p><pre>...</pre><pre>//Create User<br>router.delete(&#39;/delete-user/:id&#39;, AuthController.deleteUsers)<br>...</pre><p>For controlling the logic create the controller file ./ src/controller/user.js.</p><pre>...</pre><pre>static deleteUser = async (req, res) =&gt; {<br>    try {<br>     const user = await User.findByIdAndDelete(req.params.id) <br> <br>     if (!user) {<br>         return res.status(404).send({<br>                                      message: &quot;User Not Found&quot;<br>                                     })<br>      } <br>     res.send(user)<br>   } catch (e) {<br>     res.status(500).send({<br>                          status: 500,                          <br>                          message: e.message<br>                         })<br>   }<br>}<br>...</pre><p><strong>Start the server</strong></p><p>Start the server the same as we started on Create API</p><p><strong>Test API</strong></p><p>If your code correctly then you will get the status 200 OK and the result as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*nrJTx7cjiRMQbgTNFTHmVQ.png" /><figcaption>Result of Delete API</figcaption></figure><h3>Summary</h3><p>In this blog, we have learned to write the code for CRUD operation in NodeJs using MongoDB and Mongoose. <strong>CRUD </strong>operation stands <strong>Create Read Update Delete</strong> operation. Here, we learn the crud operation of MongoDB. We create an API for creating a user and get all users after that we create an API to update the data in the existing user and in the last we create an API to delete the user.</p><p>For the reference of the above code</p><p><a href="https://github.com/jsblend/NodeJs-CRUD-Using-MongoDB.git">jsblend/NodeJs-CRUD-Using-MongoDB</a></p><p>Feel free to connect with us read more articles from <a href="http://www.aeologic.com/">Aeologic.com</a>.</p><p><a href="http://www.aeologic.com/"><strong>Aeologic Technologies</strong></a> is a dynamic, solution, and value-driven technology company. We position ourselves as a new generation cutting edge technology company. We work creatively to enable businesses with leading technologies and solutions. You can connect with us on <a href="https://www.facebook.com/AeoLogicTech/">Facebook</a>, <a href="https://twitter.com/aeologictech">Twitter</a>, and <a href="https://www.linkedin.com/company/aeologic-technologies/">LinkedIn </a>for any queries.</p><figure><a href="https://www.aeologic.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GM5-_fTVNgVFfWJznrY2cg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ba129d72df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jsblend/crud-operation-c5ba129d72df">Crud Operation</a> was originally published in <a href="https://medium.com/jsblend">jsblend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>