<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: INDRANIL MAITI</title>
    <description>The latest articles on DEV Community by INDRANIL MAITI (@indraphoton).</description>
    <link>https://dev.to/indraphoton</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1420878%2F73c58a24-b7bb-4013-8583-0614568b88ac.png</url>
      <title>DEV Community: INDRANIL MAITI</title>
      <link>https://dev.to/indraphoton</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/indraphoton"/>
    <language>en</language>
    <item>
      <title>Stack and Heap: Memory in Javascript</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Sat, 21 Jun 2025 13:08:11 +0000</pubDate>
      <link>https://dev.to/indraphoton/stack-and-heap-memory-in-javascript-a25</link>
      <guid>https://dev.to/indraphoton/stack-and-heap-memory-in-javascript-a25</guid>
      <description>&lt;p&gt;The concept of memory is very important in Javascript and today we will deep dive into this. At the end this concept of memory allocation will be helpful to understand another important concept of serialization and deserialization.&lt;br&gt;
There are two types of memory allocation one is Stack and another is Heap memory. In JavaScript, primitive values (such as numbers, strings, booleans, etc.) are stored in the stack, while objects (such as arrays, objects etc.) are stored in the heap.&lt;/p&gt;

&lt;p&gt;Primitive values are immutable and have a fixed size, so they can be easily stored and accessed in the stack. Objects are mutable and have a variable size, so they need to be stored and accessed in the heap, which is more flexible but also slower.&lt;br&gt;
The main difference between stack and heap memory is stack memory is fixed and can't grow over but on the other hand heap memory can grow. For example, if you write an array or object the length of the array can be of any value. It can be 5 or 50 i.e. it can grow. &lt;br&gt;
Let's see some example to get e more in depth understanding.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fname = "John"; // string literal, stored in stack memory
let lname = "Doe"; // string literal, stored in stack memory

let newfname = fname

console.log(`First Name: ${fname}, Last Name: ${lname}`); // Accessing string literals from stack memory
console.log(`New First Name: ${newfname}`); // Accessing new variable from stack memory

//output
First Name: John, Last Name: Doe
New First Name: John
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we have created a variable &lt;code&gt;fname&lt;/code&gt; and assigned a value to it. Then we created another variable &lt;code&gt;newfname&lt;/code&gt; and made it equal to &lt;code&gt;fname&lt;/code&gt;.&lt;br&gt;
Let's play with this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fname = "John"; // string literal, stored in stack memory
let lname = "Doe"; // string literal, stored in stack memory

let newfname = fname

console.log(`First Name: ${fname}, Last Name: ${lname}`); // Accessing string literals from stack memory
console.log(`New First Name: ${newfname}`); // Accessing new variable from stack memory

newfname = "Jane"; // Reassigning newfname, now it points to a new string literal in stack memory
console.log(`Updated First Name: ${fname}`); // Accessing original fname
console.log(`Updated New First Name: ${newfname}`); // Accessing updated newfname

//output
First Name: John, Last Name: Doe
New First Name: John
Updated First Name: John
Updated New First Name: Jane
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have made some changes to &lt;code&gt;newfname&lt;/code&gt; and print the variables. As expected the &lt;code&gt;newfname&lt;/code&gt; is different than &lt;code&gt;fname&lt;/code&gt;&lt;br&gt;
This is &lt;strong&gt;stack&lt;/strong&gt; memory where a seperate memory has been allocated to variables and a change in one varible does not affect the other. &lt;/p&gt;

&lt;p&gt;Let's go one step furthur and see another example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person = {
    fname: "John",
    lname: "Doe"
};

let newPerson = person; // newPerson references the same object in heap memory
newPerson.fname = "Jane"; // Modifying the object through newPerson
newPerson.lname = "Smith"; // Modifying the object through newPerson

console.log(`Person First Name: ${person.fname}, Last Name: ${person.lname}`); // Accessing modified object
console.log(`New Person First Name: ${newPerson.fname}, Last Name: ${newPerson.lname}`); // Accessing modified object through newPerson

//output
Person First Name: Jane, Last Name: Smith
New Person First Name: Jane, Last Name: Smith
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like previous example, I we have created an object here &lt;code&gt;person&lt;/code&gt; and assigned the same to &lt;code&gt;newperson&lt;/code&gt;. But to the most surprise when we changed the &lt;code&gt;newPerson&lt;/code&gt; the changes has been done to &lt;code&gt;person&lt;/code&gt; variable too which is quite different than previous case!&lt;br&gt;
The answer is &lt;strong&gt;heap&lt;/strong&gt; memory. All the variables that can grow like arrays, objects are stored in heap memory and the address of the variable is stored in the stack memory. As a result &lt;code&gt;person&lt;/code&gt; is actually the address from the memory. Actually for this case when you do &lt;code&gt;let newPerson = person&lt;/code&gt; the address of the &lt;code&gt;person&lt;/code&gt; have been assigned to &lt;code&gt;newPerson&lt;/code&gt; and eventually both &lt;code&gt;person&lt;/code&gt; and &lt;code&gt;newperson&lt;/code&gt; points to same variable thorugh the same address in the heap memory. As a result when you make changes in one variable the other one changes. &lt;/p&gt;

&lt;p&gt;I hope the difference of stack and heap memory is clear now. Now we will deep dive into another interesting topic.&lt;/p&gt;
&lt;h2&gt;
  
  
  Deep Copy and Shallow copy
&lt;/h2&gt;

&lt;p&gt;In the previous example with person and newPerson, we saw that when you assign one object to another, any change in one reflects in the other. This is because both variables point to the same address in the heap memory, not separate ones.&lt;/p&gt;

&lt;p&gt;That’s called a shallow copy — where only the reference (i.e., memory address) is copied, not the actual object.&lt;/p&gt;

&lt;p&gt;Let’s make it more interesting with another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person1 = {
    fname: "John",
    lname: "Doe",
    details: {
        age: 30,
        city: "New York"
    }
};

let person2 = person1; // shallow copy

person2.fname = "Jane";
person2.details.age = 25;

console.log(person1);
console.log(person2);

//output
{
  fname: 'Jane',
  lname: 'Doe',
  details: { age: 25, city: 'New York' }
}
{
  fname: 'Jane',
  lname: 'Doe',
  details: { age: 25, city: 'New York' }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, changing &lt;code&gt;person2&lt;/code&gt; also changes &lt;code&gt;person1&lt;/code&gt;— even the nested property &lt;code&gt;details.age&lt;/code&gt;. That’s because both &lt;code&gt;person1&lt;/code&gt;and &lt;code&gt;person2&lt;/code&gt;refer to the same object in heap memory. &lt;/p&gt;

&lt;h2&gt;
  
  
  A Better Way? Using Object Spread ...
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person2 = { ...person1 };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is also a shallow copy. It only creates a new top-level object, but nested objects are still shared via reference.&lt;/p&gt;

&lt;p&gt;So, modifying a nested property will still affect the original:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person2 = { ...person1 };
person2.details.city = "Chicago";

console.log(person1.details.city); // Chicago

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, same problem — nested values are not copied deeply.&lt;/p&gt;

&lt;h2&gt;
  
  
  Enter Deep Copy — the Reliable Way
&lt;/h2&gt;

&lt;p&gt;To really copy the entire structure, including nested objects, we need a deep copy.&lt;/p&gt;

&lt;p&gt;One simple way (especially for objects with no functions or special types) is to use JSON.stringify() and JSON.parse():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person1String = JSON.stringify(person1);
let person2 = JSON.parse(person1String); // Deep copy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method works because:&lt;/p&gt;

&lt;p&gt;JSON.stringify() turns your object into a string (i.e., serializes it)&lt;/p&gt;

&lt;p&gt;JSON.parse() creates a brand-new object from that string (i.e., deserializes it)&lt;/p&gt;

&lt;p&gt;Now, person2 is completely separate from person1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;person2.details.city = "Los Angeles";

console.log(person1); 
// Original object remains unchanged

console.log(person2); 
// Shows updated city

//output
{
  fname: 'John',
  lname: 'Doe',
  details: { age: 30, city: 'New York' }
}
{
  fname: 'John',
  lname: 'Doe',
  details: { age: 30, city: 'Los Angeles' }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, What’s Happening Here?&lt;br&gt;
This is where serialization and deserialization comes in.&lt;/p&gt;

&lt;p&gt;Serialization means converting your object into a string format (JSON.stringify()), which can be stored or sent over a network.&lt;/p&gt;

&lt;p&gt;Deserialization means converting that string back into an object (JSON.parse()), often creating a new one in memory.&lt;/p&gt;

&lt;p&gt;This concept is not only useful for making deep copies, but also essential when working with:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;APIs and network requests&lt;/li&gt;
&lt;li&gt;Local storage in the browser&lt;/li&gt;
&lt;li&gt;Sending or saving data&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Wrapping It Up&lt;br&gt;
Let’s quickly summarize what we’ve learned:&lt;/p&gt;

&lt;p&gt;Stack memory is used for primitive types (string, number, boolean), and every variable gets its own copy.&lt;/p&gt;

&lt;p&gt;Heap memory is used for objects (arrays, objects, functions), and variables store references (addresses).&lt;/p&gt;

&lt;p&gt;Shallow copy copies the reference, not the actual object.&lt;/p&gt;

&lt;p&gt;Deep copy duplicates the entire object structure — including nested objects — often using JSON.stringify() and JSON.parse().&lt;/p&gt;

&lt;p&gt;Serialization and deserialization are powerful tools not just for copying, but for transmitting and storing complex data.&lt;/p&gt;

&lt;p&gt;Understanding how memory works in JavaScript can save you from confusing bugs and give you a solid foundation for working with real-world apps.&lt;/p&gt;

&lt;p&gt;Thanks for reading! 🚀&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>🤖How My AI Agent Transformed Video Research from Hours to Minutes🤯</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Wed, 11 Jun 2025 09:29:45 +0000</pubDate>
      <link>https://dev.to/indraphoton/how-my-ai-agent-transformed-video-research-from-hours-to-minutes-3469</link>
      <guid>https://dev.to/indraphoton/how-my-ai-agent-transformed-video-research-from-hours-to-minutes-3469</guid>
      <description>&lt;p&gt;I find it very hard to get proper tags, or descriptions when uploading my videos on YouTube. There is an option to use ChatGPT but I want to check it more exclusively in a particular niche. &lt;/p&gt;

&lt;p&gt;I thought let's build an AI agent that will analyze 100s of videos in the AI niche and suggest metadata, tags, and description for me. Therefore I built an AI agent to do these tasks for me. &lt;br&gt;
If you prefer to watch a video than reading a blog here it is&lt;br&gt;
  &lt;iframe src="https://www.youtube.com/embed/jrxKpL8pwDk"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;I will be using NebiusAI for LLM integration and CrewAI for agent handling. I have written a simpler version on how to build an AI agent using these in my previous article. &lt;br&gt;
Here is the link : &lt;a href="https://dev.to/indraphoton/how-to-build-a-simple-ai-agent-using-crewai-and-nebiusai-22mk"&gt;https://dev.to/indraphoton/how-to-build-a-simple-ai-agent-using-crewai-and-nebiusai-22mk&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So let's get started&lt;/p&gt;
&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;At the very first step, you need to install crewai tools for this. We will be using some custom tools built by CrewAI to scrap the youtube data and write an analysis.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install 'crewai[tools]'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  LLM Integration
&lt;/h2&gt;

&lt;p&gt;Next we have to bring the LLM for our work. We will be using Nebius AI studio for this purpose. You will also need to have &lt;code&gt;NEBIUS_API_KEY&lt;/code&gt; from Nebius to use the LLM model. You need to signup first and create an API key there. Don't forget to put your API key in the environment variable (.env)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from dotenv import load_dotenv
load_dotenv()

default_llm=LLM(
        model="openai/meta-llama/Meta-Llama-3.1-70B-Instruct",
        base_url="https://api.studio.nebius.com/v1/",
        api_key=os.getenv("NEBIUS_API_KEY")
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Agent Building
&lt;/h2&gt;

&lt;p&gt;After integrating the LLM model, we need to create the agent for data handling and its analysis. We will build two agent here one will bring the data and the other one will write the report for me. For this we will use &lt;code&gt;YoutubeVideoSearchTool&lt;/code&gt; and &lt;code&gt;YoutubeChannelSearchTool&lt;/code&gt; from crewAI tool here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from crewai import Agent, Task, LLM
from crewai import Crew, Process
from crewai_tools import SerperDevTool, YoutubeVideoSearchTool, YoutubeChannelSearchTool
#agent 1
researcher = Agent(
    role="youtube video details e.g. tiltle, description, tags, channel analysis",
    goal="Uncover the hidden tags, title, description, and channel analysis of YouTube videos in a specific niche.",    
    backstory="You are an expert in YouTube video analysis, specializing in extracting detailed metadata and insights from videos.",
    tools=[YoutubeVideoSearchTool(), YoutubeChannelSearchTool()],
    llm=default_llm
)

#agent 2
writer = Agent(
    role="Report Writer",
    goal="Write a compelling report on the YouTube video analysis findings focusing on numbers views tags title, description, and channel " \
    "analysis. Try to find the most popular videos in the niche and its success factors. write in a professional tone, to the point, "
    "and with a focus on actionable insights. Use bullet points for clarity. focus on numbers.",
    verbose=True,
    llm=default_llm,
    backstory="You excel at translating complex data into readable content, focusing on actionable insights and clarity.",
    tools=[]
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Assign the task for each agent
&lt;/h2&gt;

&lt;p&gt;Once the agent is built we need to assign the task to each agent. Here is the step&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;research_task = Task(
    description="Research the successful YouTube videos in the niche of AI agents, focusing on their tags, titles, descriptions, and channel analysis.",
    expected_output="A report summarizing key insights from the YouTube videos, including tags, titles, descriptions, and channel analysis.",
    agent=researcher  # Assign the researcher agent
)

write_task = Task(
    description="Write a detailed report based on the YouTube video analysis findings, focusing on numbers views tags title, description, and channel analysis.",
    expected_output="An engaging report on the YouTube video analysis findings, highlighting key metrics and insights.",
    agent=writer,  # Assign the writer agent
    context=[research_task]  # Use research task output as context
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Instantiate the agent crew
&lt;/h2&gt;

&lt;p&gt;We have everything set up. This is time to create the agent instance so that it starts to give answer when asked. The process can be sequential or Hierarchical.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    process=Process.sequential  # The agents work in sequence
)
# Execute the crew and capture the result
result = crew.kickoff(inputs={"topic": "AI agents in YouTube videos"})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are done. Here is the output.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwcqwbgtja1owrhbspc4o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwcqwbgtja1owrhbspc4o.png" alt=" "&gt;&lt;/a&gt;&lt;br&gt;
You will get the full &lt;a href="https://github.com/Indra-photon/ai-agent/tree/master/crewAI_starter" rel="noopener noreferrer"&gt;code here&lt;/a&gt;,&lt;br&gt;
Today we have built the most simple AI agent using crewAI and NebiusAI. You can use this idea to build some other applications. Let me know what ideas you are building, share your experience here. &lt;/p&gt;

</description>
      <category>ai</category>
      <category>agents</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>All About Functions in Javascript</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Mon, 09 Jun 2025 08:41:49 +0000</pubDate>
      <link>https://dev.to/indraphoton/all-about-functions-in-javascript-3446</link>
      <guid>https://dev.to/indraphoton/all-about-functions-in-javascript-3446</guid>
      <description>&lt;p&gt;Functions are one of the main fundamental building blocks of Javascript.  These are necessary for building web applications. Before going into details, let us have some motivation. &lt;/p&gt;

&lt;h2&gt;
  
  
  Motivation
&lt;/h2&gt;

&lt;p&gt;In our daily life, certain tasks are handled by specific people who specialize in them. For example, when you need a piece of furniture, you go to a carpenter. In the same way, in web applications, functions are created to handle specific tasks.&lt;/p&gt;

&lt;p&gt;Let’s say in your application you need to access user data—like their username or subscription status—at multiple places. You have two choices: either you write the same logic every single time, or you write it once as a function and simply call that function wherever it's needed.&lt;/p&gt;

&lt;p&gt;Clearly, the second option is a game-changer, right?&lt;br&gt;
It not only saves you from repeating code but also gives your application a neat and modular structure.&lt;/p&gt;

&lt;p&gt;Don’t worry if this feels a bit new—we’ll make it clearer as we go deeper into the topic!&lt;/p&gt;
&lt;h2&gt;
  
  
  Structure of a Function
&lt;/h2&gt;

&lt;p&gt;As we have understood from the previous section function is a set of instructions that performs a task. There is also a superpower to function that it can take some inputs which it processes through the set of instructions you have given and gives us the output. &lt;br&gt;
Let us have an example, you are looking to build a function that calculates the total price of the customer's cart before checkout. So you want a simple addition of prices (this is the task of the function). But to perform this task, you need to provide the amount as input of the function. These are called parameters. &lt;br&gt;
Let us see an example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function calculateTotal(prices) {
  let total = 0;
  for (let i = 0; i &amp;lt; prices.length; i++) {
    total += prices[i];
  }
  return total;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A function definition consists of the &lt;code&gt;function&lt;/code&gt; keyword followed by &lt;br&gt;
    - The name of the function. Here it is &lt;code&gt;calculateTotal&lt;/code&gt;&lt;br&gt;
    - A list of parameters to the function, enclosed in parentheses and separated by commas. Here it is &lt;code&gt;prices&lt;/code&gt;&lt;br&gt;
    - The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }. Here it is &lt;code&gt;let total = 0;&lt;br&gt;
  for (let i = 0; i &amp;lt; prices.length; i++) {&lt;br&gt;
    total += prices[i];&lt;br&gt;
  }&lt;br&gt;
  return total;&lt;/code&gt;&lt;br&gt;
An important note: Generally there should be an &lt;code&gt;return&lt;/code&gt; statement at the end of the function which will be the function's output. Also, a function can return another function as well!&lt;/p&gt;
&lt;h2&gt;
  
  
  How to Use the function
&lt;/h2&gt;

&lt;p&gt;This is pretty simple. Just Call the function by its name along with the parameters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cart = [29.99, 15.50, 9.99];
const totalPrice = calculateTotal(cart)
console.log(totalPrice)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Function Expression
&lt;/h2&gt;

&lt;p&gt;The above way of representing the function is generally known as &lt;strong&gt;Function Declaration&lt;/strong&gt;. There is another kind of representation of functions which is known as &lt;strong&gt;Function Expression&lt;/strong&gt;. The representation in this case is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const calculateTotal = function (prices) {
  let total = 0;
  for (let i = 0; i &amp;lt; prices.length; i++) {
    total += prices[i];
  }
  return total;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main difference here is you can omit the name of the function. &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use Function Expressions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Callbacks &amp;amp; Event Handlers&lt;/strong&gt;&lt;br&gt;
Use Case: Responding to user actions like clicking a button.You can define the logic inline without needing a separate named function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById("subscribeBtn").addEventListener("click", function () {
  alert("Thank you for subscribing!");
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.  Defining Methods Inside Objects&lt;/strong&gt;&lt;br&gt;
Use Case: Creating an object with methods for business logic. Method is defined inline inside the object, making the structure clean and readable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cart = {
  items: [],
  addItem: function (item) {
    this.items.push(item);
    console.log(`${item} added to cart.`);
  },
};
cart.addItem("T-shirt"); // T-shirt added to cart.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Conditional or Dynamic Logic&lt;/strong&gt;&lt;br&gt;
Use Case: Define different functions based on user role or environment. Assign function dynamically based on condition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = { isAdmin: true };

const accessControl = user.isAdmin
  ? function () {
      console.log("Access granted to admin panel.");
    }
  : function () {
      console.log("Access denied.");
    };

accessControl(); // Output depends on user role

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Arrow Function
&lt;/h2&gt;

&lt;p&gt;There is a compact alternative to Function Expressions in modern day web applications. This is known as &lt;strong&gt;Arrow Function&lt;/strong&gt;. The most common syntax is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(params) =&amp;gt; {
  statements
}
//Example
(a, b) =&amp;gt; {
  return a + b + 100;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the body has statements, the braces are required — and so is the return keyword. The braces can only be omitted if the function directly returns an expression.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(a,b) =&amp;gt; a+b+100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Lexical Scope and Closure
&lt;/h2&gt;

&lt;p&gt;There is one more important concept related to functions in Javascript i.e. &lt;code&gt;Lexical Scope&lt;/code&gt; and &lt;code&gt;Closure&lt;/code&gt;. Lexical scope is known as how the variables defined in the function can be accessed based on the placement of the variable. Let us see an example to understand this better&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outer() {
  const message = "Hello, ";

  function inner(name) {
    console.log(message + name);
  }

  return inner;
}

const greet = outer();
greet("Alice"); // Outputs: Hello, Alice
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;message&lt;/code&gt; variable is defined in the &lt;code&gt;outer&lt;/code&gt; function and &lt;code&gt;outer&lt;/code&gt; function also has another function defined as &lt;code&gt;inner&lt;/code&gt;. Look &lt;code&gt;outer&lt;/code&gt; function is returning the function &lt;code&gt;inner&lt;/code&gt;. &lt;br&gt;
Here, &lt;code&gt;inner&lt;/code&gt; function has access to the variable &lt;code&gt;message&lt;/code&gt; though it has been defined outside &lt;code&gt;inner&lt;/code&gt; function. This is because javascript uses lexical scoping means it looks for variables where the function was defined. Here &lt;code&gt;inner&lt;/code&gt; function is inside the scope of &lt;code&gt;outer&lt;/code&gt; function. On the other hand &lt;code&gt;outer&lt;/code&gt; function does not have any access to any variable defined in &lt;code&gt;inner&lt;/code&gt; function because any variable defined &lt;code&gt;inner&lt;/code&gt; function is not inside the scope of &lt;code&gt;outer&lt;/code&gt; fucntion.&lt;/p&gt;

&lt;p&gt;On the other hand, a closure is closely related to lexical scope. It occurs when a function “remembers” the variables from its outer lexical scope, even after that outer function has finished executing. This behavior allows functions to maintain access to their parent’s variables, even if they would normally go out of scope.&lt;br&gt;
Let's see an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function init() {
  var name = "Indra";
  function displayName() {
    console.log(name); 
  }
  displayName();
}
let res = init();
res() // output: Indra

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look very carefully here, &lt;code&gt;let res = init()&lt;/code&gt; in this line &lt;code&gt;init&lt;/code&gt; function has been executed so you might think the variable &lt;code&gt;name&lt;/code&gt; does not exist anymore and we might get an error while calling the function &lt;code&gt;res()&lt;/code&gt; in the next line. Here comes the context of closure. In JS when you call the function &lt;code&gt;init()&lt;/code&gt; in the &lt;code&gt;res&lt;/code&gt; variable not only the &lt;code&gt;displayName&lt;/code&gt; function comes but it comes along with the lexical scope of &lt;code&gt;init&lt;/code&gt; function too.&lt;/p&gt;

&lt;p&gt;I hope this helps you in understanding the concept of Function in Javascript.   &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>How to Build a simple AI agent using crewAI and NebiusAI</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Thu, 05 Jun 2025 08:35:04 +0000</pubDate>
      <link>https://dev.to/indraphoton/how-to-build-a-simple-ai-agent-using-crewai-and-nebiusai-22mk</link>
      <guid>https://dev.to/indraphoton/how-to-build-a-simple-ai-agent-using-crewai-and-nebiusai-22mk</guid>
      <description>&lt;p&gt;Today I will build a simple AI agent using CrewAI and NebiusAI. CrewAI is a growing platform for multiagent automation. With NebiusAI it is very simple to build an AI agent that will answer user's query. We will build an AI agent today that will answer. THe goal is to understand first how CrewAI works in a most simplest easy to understand way. &lt;br&gt;
In case you prefer to watch youtube video than reading blog you can check here&lt;br&gt;
   &lt;iframe src="https://www.youtube.com/embed/TnQ6wRydKPQ"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Installations
&lt;/h2&gt;

&lt;p&gt;You need to install crewai to utilize the ai agent by them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install crewai python-dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will also need to have &lt;code&gt;NEBIUS_API_KEY&lt;/code&gt; from Nebius to use the LLM model. You need to signup first and create an API key there. Don't forget to put your API key in the environment variable (.env)&lt;/p&gt;

&lt;h2&gt;
  
  
  LLM Model
&lt;/h2&gt;

&lt;p&gt;We need to bring the LLM models first using nebius.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from dotenv import load_dotenv
load_dotenv()

default_llm=LLM(
        model="openai/meta-llama/Meta-Llama-3.1-70B-Instruct",
        base_url="https://api.studio.nebius.com/v1/",
        api_key=os.getenv("NEBIUS_API_KEY")
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create an Agent
&lt;/h2&gt;

&lt;p&gt;Once we have brought the LLM model now we can create the agent using crewAI. You have to set &lt;code&gt;role, goal&lt;/code&gt; and &lt;code&gt;backstory&lt;/code&gt; for the agent to get better output. Try playing with these and check how different are the results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from crewai import Agent, Task,LLM
researcher = Agent(
  role='Senior Researcher',
  goal='Discover groundbreaking technologies in quantum computing',
  verbose=True,
  llm=default_llm,
  backstory='A curious mind fascinated by cutting-edge innovation and the potential to change the world, you know everything about quantum computing and its applications.',
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Set the task for the agent
&lt;/h2&gt;

&lt;p&gt;We have created our agent and now it's the time to setup tasks for the agent.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Task for the researcher
research_task = Task(
  description='Identify the next big trend quantum computing will enable',
  expected_output='5 paragraphs on the future of quantum computing and its potential applications',
  agent=researcher  # Assigning the task to the researcher
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Instantiate the agent crew
&lt;/h2&gt;

&lt;p&gt;We have everything set up. This is time to create the agent instance so that it starts to give answer when asked. The process can be sequential or parallel. In this case we will use sequential but if your project cotntains multi-agent and needs parallel work you have to choose parallel in &lt;code&gt;process=Process.sequential&lt;/code&gt;. We will see such examples next day.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Instantiate your crew
tech_crew = Crew(
  agents=[researcher],
  tasks=[research_task],
  process=Process.sequential  # Tasks will be executed one after the other
)
# Begin the task execution
tech_crew.kickoff()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now once you run this file you will get the output.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7y5w0grnun4di3cph2rw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7y5w0grnun4di3cph2rw.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will get the full code &lt;a href="https://github.com/Indra-photon/ai-agent/tree/master/crewAI_starter" rel="noopener noreferrer"&gt;here&lt;/a&gt;,&lt;br&gt;
Today we have built the most simple AI agent using crewAI and NebiusAI. In the next post we will see how multiple agents can work and also how we can integrate tools like google search for building more upgraded AI agent. &lt;/p&gt;

</description>
      <category>agents</category>
      <category>genai</category>
      <category>softwaredevelopment</category>
      <category>webdev</category>
    </item>
    <item>
      <title>I Built My First SaaS — Here’s The Mistakes I did</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Wed, 04 Jun 2025 14:47:15 +0000</pubDate>
      <link>https://dev.to/indraphoton/i-built-my-first-saas-heres-the-mistakes-i-did-46ic</link>
      <guid>https://dev.to/indraphoton/i-built-my-first-saas-heres-the-mistakes-i-did-46ic</guid>
      <description>&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/9UuVTOeTKKw"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;I have recently launched my first ever SaaS, ToonyTalesWorld where user can create colourful personalized storybooks for kids and feature them as hero in their own story. &lt;br&gt;
CHeck out my project on Peerlist Launchpad. &lt;a href="https://peerlist.io/indranil/project/toonytalesworld" rel="noopener noreferrer"&gt;Check this out&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvepb1ua7nb04h3ax1dnj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvepb1ua7nb04h3ax1dnj.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is my first ever SaaS so I made too many mistakes and it took around 3 months for me to finish this as a product. The mistakes are silly but were unavoidable as I did not have any experience. But before mentioning them I also want to tell you this is an incredible journey my friend. Once you come out from the project building mindset to product building mindset you will feel the difference. As a solo developer I enjoyed every part of it from buying domains, marketing, to pricing selection this was an incredible journey. &lt;/p&gt;

&lt;p&gt;So, without wasting more time here are the mistakes&lt;/p&gt;

&lt;h2&gt;
  
  
  Not Enough Planning
&lt;/h2&gt;

&lt;p&gt;I did not plan enough before the start of the project and from the day one I started coding. After spending one month I understood the need of PRD. Before starting any project spend enough time on PRD and have clear planning of your different phase development. It is good to build phase by phase and take opinions from your user. Don't try to overdo and make everything perfect before launch. It will eventually be perfect on the way. At this stage you should have clear answer of two questions 1. What you are building  2. For whom you are building &lt;/p&gt;

&lt;h2&gt;
  
  
  Your Competitions
&lt;/h2&gt;

&lt;p&gt;PLease do spend some time on market research before building a product. YOu will also get an opportunity to validate your idea, pricing structure your competitors are using, and these will save a lot of time later on. i had to spend an enormous amount of time later stage which should have been done earlier. Don't do this mistake&lt;/p&gt;

&lt;h2&gt;
  
  
  Techstack and cost analysis
&lt;/h2&gt;

&lt;p&gt;in your local development you may not need some professional services for an example mailing services but in production you need such services and it also comes with a cost. So apart from the domain and server there will be more cost associated with your product. research about these services finalize the tiers you will use and make the pricing tiers according to your costs otherwise it will be so much frustrating at the end. &lt;/p&gt;

&lt;h2&gt;
  
  
  Hype Yourself
&lt;/h2&gt;

&lt;p&gt;In today's world, you have to sell yourself. PLan your marketing and start engaging with people before launching it. &lt;/p&gt;

&lt;p&gt;These were my key learnings from my first SaaS. At the end don't forget to check out &lt;a href="https://peerlist.io/indranil/project/toonytalesworld" rel="noopener noreferrer"&gt;ToonyTalesWorld&lt;/a&gt; at peerlist and please do a upvote if you like the project.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>saas</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Step-by-Step: Build a RAG Chatbot That Understands Your PDFs</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Mon, 26 May 2025 08:45:26 +0000</pubDate>
      <link>https://dev.to/indraphoton/step-by-step-build-a-rag-chatbot-that-understands-your-pdfs-5ai0</link>
      <guid>https://dev.to/indraphoton/step-by-step-build-a-rag-chatbot-that-understands-your-pdfs-5ai0</guid>
      <description>&lt;p&gt;Today, we will build a simple chatbot that answers based on your pdf. We will use Langchain and Openai. The goal is to learn the basics of a simple RAG application. Before beginning lets understand the steps. For building a basic RAG application you need to understand the 5 steps. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;Loading Documents&lt;/em&gt; : First you need to load your data be it PDF, or CSV, excel, or website. &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Split&lt;/em&gt; : You need to then split your data. This is needed because every LLM has its own context window. So if your data is big you can not give all the data at once to LLM to get preferred output.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Embeddings&lt;/em&gt;: To store the data in the database we need to make embeddings. &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Store&lt;/em&gt; : As the embeddings is done final work is to store it in the database.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq0rbbqdkgsoe3e9o0638.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq0rbbqdkgsoe3e9o0638.png" alt="Image description" width="800" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;Retrieval&lt;/em&gt; : Now, as the user asks some question to LLM, relevant chunks of data will be retrieved from the database and will be given to the LLM context. LLM will give the output based on chunks it has received.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu9hcexuttw6dp86i1wa6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu9hcexuttw6dp86i1wa6.png" alt="Image description" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Without wasting any time let's get started. &lt;/p&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;We need to install the following packages. I will tell about the need of these packages in the subsequent sections.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;%pip install -qU pypdf
%pip install -qU langchain-openai
%pip install -qU langchain-qdrant
%pip install langchain_text_splitters
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need a OPENAI_API_KEY as well. So if you do not have please create it. After creating it we have to load the key from the .env file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from dotenv import load_dotenv
load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Load your PDF
&lt;/h2&gt;

&lt;p&gt;To make a chatbot based on your pdf we have to load the pdf first and for this we will use &lt;code&gt;PyPDFLoader&lt;/code&gt; from &lt;code&gt;langchain_community&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain_community.document_loaders import PyPDFLoader

file_path = "YOUR_FILE_PATH"

loader = PyPDFLoader(file_path)
pages = []
async for page in loader.alazy_load():
    pages.append(page)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Split the text
&lt;/h2&gt;

&lt;p&gt;As we have loaded the PDF successfully, we now have to split the text for breaking it into chunks. Later the relevant chunks will be taken based on the user's query. We have used RecursiveCharacterTextSplitter but there are other options as well. Read &lt;a href="https://dev.toRecursiveCharacterTextSplitter"&gt;here&lt;/a&gt;. You can choose different splitters and watch the performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter  = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200,
)

split_docs = text_splitter.split_documents(documents = pages)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Chunk size defines how much information it should contain. You can change and play to know what's the correct number to get correct responses. Chunk overlap means a chunk will start not just after the end of the previous chunk but it will contain some information from previous chunk. This helps to maintain the context of the PDF. &lt;/p&gt;

&lt;h2&gt;
  
  
  Embeddings
&lt;/h2&gt;

&lt;p&gt;Next step is to make embeddings from the chunks. We will use OpenAI embeddings here from langchain. You can choose any other embeddings as well. Check &lt;a href="https://python.langchain.com/docs/integrations/text_embedding/" rel="noopener noreferrer"&gt;here&lt;/a&gt; for other embeddings models.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(
    model = "text-embedding-3-large",
    api_key = os.environ["OPENAI_API_KEY"],
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have created our embedder and will use this while uploading the chunks into database. &lt;/p&gt;

&lt;h2&gt;
  
  
  Store chunks in the Database
&lt;/h2&gt;

&lt;p&gt;Next step is to store the chunks in the database. For this we will use QdrantDB from langchain. This is open source and easy to use. You need to have docker installed in your local computer and you can run it very easily. &lt;br&gt;
After docker installation simply run a docker-compose.yml file to run the qdrantdb. Here is the .yml file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services:
  qdrant:
    image: qdrant/qdrant
    ports:
      - 6333:6333
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once it runs go to &lt;code&gt;http://localhost:6333/dashboard&lt;/code&gt; to check if qdrant has run successfully or not. If you see the following then its working. for your case there should not be any db store. &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1zrq65panb6uer1z9qej.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1zrq65panb6uer1z9qej.png" alt="Image description" width="800" height="350"&gt;&lt;/a&gt;&lt;br&gt;
Keep the docker running as it is and let's move on to the next step. So far we have created the chunks. &lt;br&gt;
First we have to create a client to connect with the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain_qdrant import QdrantVectorStore
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams
# Create the client
client = QdrantClient(url="http://localhost:6333")

# Create the collection with the correct embedding dimension
client.create_collection(
    collection_name="visual_instruction_final",
    vectors_config=VectorParams(
        size=3072,  # Your embedding dimension
        distance=Distance.COSINE
    )
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we will use this client to upload the chunks into database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Now create the vector store using the existing collection
vector_store = QdrantVectorStore(
    client=client,  # Use the client we created in Step 2
    collection_name="visual_instruction_final",
    embedding=embeddings
)

# Add your documents
vector_store.add_documents(split_docs)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once this is successful you can check the dashboard again by refreshing it and you will see the datas stored there. &lt;/p&gt;

&lt;h2&gt;
  
  
  Information Retrieval
&lt;/h2&gt;

&lt;p&gt;Now the most fun part, is to retrieve the data based on user's query. The most important part now you can imagine, based on the user's query the most important chunks will be retrieved from the database and provided to the LLM models. LLM models will then prepare the response. &lt;br&gt;
Here is how you can write the retriever.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain_qdrant import QdrantVectorStore

# Create retriever without passing the client object
retriever = QdrantVectorStore.from_existing_collection(
    collection_name="visual_instruction_final",
    embedding=embeddings,
    url="http://localhost:6333"  # Use URL instead of client
)

# Perform similarity search
search_result = retriever.similarity_search("What is written in introduction?", k=3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have done retriver based on similarity search but there are other options as well that you can change and check the performances. &lt;br&gt;
So we are all ready. Now on to the last and final step i.e. prepare the chatbot. &lt;br&gt;
We will use OpenAI from Langchain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage, AIMessage

# Create the chat model
chat_model = ChatOpenAI(
    model="gpt-3.5-turbo",  # or "gpt-4" if you have access
    temperature=0.7,        # Controls randomness (0.0 = deterministic, 1.0 = very random)
    max_tokens=1000,        # Maximum tokens in response
    streaming=False         # Set to True for streaming responses
)

def rag_chat(question, k=3):
    # Step 1: Retrieve relevant documents
    relevant_docs = retriever.similarity_search(question, k=k)

    # Step 2: Combine retrieved content
    context = "\n\n".join([doc.page_content for doc in relevant_docs])

    # Step 3: Create messages directly (simpler approach)
    system_message = f"""You are a helpful AI assistant. Use the following context to answer the user's question. 
If you can't find the answer in the context, say so clearly.

Context:
{context}"""

    messages = [
        SystemMessage(content=system_message),
        HumanMessage(content=question)
    ]

    # Step 4: Get response from chat model
    response = chat_model.invoke(messages)

    return {
        "answer": response.content,
        "sources": relevant_docs,
        "context_length": len(context)
    }

# Test the corrected RAG chatbot
question = "What is written in introduction?"
result = rag_chat(question)

print("Question:", question)
print("\nAnswer:", result["answer"])
print(f"\nContext length: {result['context_length']} characters")
print(f"Used {len(result['sources'])} source documents")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Last few lines have been added here to check the retrieved chunks. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8xsipxzv4jduhkf2hcwd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8xsipxzv4jduhkf2hcwd.png" alt="Image description" width="800" height="312"&gt;&lt;/a&gt;&lt;br&gt;
Once you run this, you will get the response from the LLM. Now you can play with different options and try to get a better response. The main goal here was to introduce the concept step by step and how to use them. Hope this clears. Happy building..&lt;br&gt;
Share what you are building. &lt;br&gt;
Connect me : &lt;a href="https://x.com/Nil_phy_dreamer" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rag</category>
      <category>ai</category>
      <category>tutorial</category>
      <category>openai</category>
    </item>
    <item>
      <title>Understanding NodeJS STREAMS : Reading the Data in chunks (Part I)</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Tue, 01 Apr 2025 16:06:26 +0000</pubDate>
      <link>https://dev.to/indraphoton/understanding-nodejs-streams-reading-the-data-in-chunks-part-i-50l1</link>
      <guid>https://dev.to/indraphoton/understanding-nodejs-streams-reading-the-data-in-chunks-part-i-50l1</guid>
      <description>&lt;p&gt;Streams in NodeJS are very effective way to send data from a source (or a network) to your browser bit-by-bit (or lets say chunks).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does this mean?&lt;/strong&gt;&lt;br&gt;
Suppose you have two buckets, bucket A is filled with water and the other bucket is empty. You have to send the water from bucket A to bucket B. &lt;br&gt;
There are two ways to do this. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can take another empty bucket C, take the water from bucket A and filled the bucket B&lt;/li&gt;
&lt;li&gt;Second option is take a pipe and make a connection between bucket A and B. The water will flow gradually. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The second option is exactly the same what streams mean. &lt;br&gt;
Suppose you have data (text, video, etc) received from the server and you want to show the data in your frontend. &lt;/p&gt;

&lt;p&gt;So to cut the long story short,&lt;br&gt;
&lt;em&gt;With the Streams API, you can start processing raw data with JavaScript bit by bit, as soon as it is available, without needing to generate a buffer, string, or blob&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4w50pnzsogxhm1yr37l8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4w50pnzsogxhm1yr37l8.png" alt="A diagram comparing traditional data transfer vs streaming in Node.js. The top shows the 'Traditional Approach' with a server and client connected by a large data block, labeled 'Wait for entire data to load before processing.' The bottom shows the 'Streaming Approach' with the same server and client connected by a pipe with small data chunks flowing through it, labeled 'Process data in chunks as it arrives.' On the right are four real-world applications: video streaming services, large file uploads/downloads, real-time data dashboards, and chat applications. The image illustrates how streaming allows for efficient bit-by-bit data processing" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Usecases in real life application&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Video streaming services &lt;/li&gt;
&lt;li&gt;Large file uploads/downloads &lt;/li&gt;
&lt;li&gt;Real-time data dashboards&lt;/li&gt;
&lt;li&gt;Chat applications &lt;/li&gt;
&lt;li&gt;Audio processing applications &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Enough motivation right? Lets move into technicals. Today I will talk about reading data in chunks and in the next day I will write about how you can process and use the data in chunks. &lt;/p&gt;
&lt;h2&gt;
  
  
  Using readable streams
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt; programmatically reading and manipulating streams of data received over the network, chunk by chunk&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets write code .....&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Fetch the original image
fetch("https://images.pexels.com/photos/1229356/pexels-photo-1229356.jpeg?auto=compress&amp;amp;cs=tinysrgb&amp;amp;w=600")
  // Retrieve its body as ReadableStream
  .then((response) =&amp;gt; console.log(response.body))
  .catch((err) =&amp;gt; console.log(err))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have made a request to access data from a specific URL. In this case this is an image.&lt;br&gt;
Output:&lt;br&gt;
&lt;code&gt;ReadableStream { locked: false, state: 'readable', supportsBYOB: true }&lt;/code&gt; &lt;br&gt;
Let me break it down what this output means&lt;/p&gt;

&lt;p&gt;This is showing you the properties of the ReadableStream object that represents the image data:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;locked:&lt;/em&gt; false - The stream is not currently locked by a reader. When a stream is locked, it means a reader has exclusive access to it. Since your stream is unlocked, you could still attach a reader to consume its data.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;state:&lt;/em&gt; 'readable' - The stream is in a "readable" state, which means it contains data that can be read. Other possible states include "closed" (no more data available) and "errored" (an error occurred).&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;supportsBYOB:&lt;/em&gt; true - This indicates that the stream supports "Bring Your Own Buffer" mode, which is an optimization that allows you to provide your own buffer for the stream to fill, reducing memory allocations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What we have seen the "response.body" is an ReadableStream object but not the actual data i.e. the image. To get the the data we have to consume the stream by using a reader.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch("https://images.pexels.com/photos/1229356/pexels-photo-1229356.jpeg?auto=compress&amp;amp;cs=tinysrgb&amp;amp;w=600")
  .then((response) =&amp;gt; response.body)
    .then((body) =&amp;gt; {
        const reader = body.getReader()
        console.log(reader)})
  .catch((err) =&amp;gt; console.log(err))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have attached a reader to our response which we received to read the data here. &lt;br&gt;
Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReadableStreamDefaultReader {
  stream: ReadableStream { locked: true, state: 'readable', supportsBYOB: true },
  readRequests: 0,
  close: Promise { &amp;lt;pending&amp;gt; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Invoking this method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;stream:&lt;/em&gt; This points back to the original ReadableStream from which the reader was created. Notice that now the stream has locked: true (whereas before it was false). This is because once you get a reader, it locks the stream for exclusive access.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;readRequests:&lt;/em&gt; This shows the number of pending read requests (currently 0). When you call reader.read(), this count would increment until the data is delivered.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;close:&lt;/em&gt; This is a Promise that will resolve when the stream is closed, either because all data was consumed or because the stream was explicitly canceled &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Next step is to attach &lt;em&gt;read()&lt;/em&gt; method to read data chunks out of the stream. This method returns a promise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reader.read().then(({ done, value }) =&amp;gt; {
  /* … */
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The results can be one of three different types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a chunk is available to read, the promise will be fulfilled with an object of the form { value: theChunk, done: false }.&lt;/li&gt;
&lt;li&gt;If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }.&lt;/li&gt;
&lt;li&gt;If the stream becomes errored, the promise will be rejected with the relevant error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So now we have understood how the .read() works. Lets write down the code to read the full data in chunks. &lt;br&gt;
First we will create a function to read all chunks from a reader.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function to read all chunks from a reader
function readAllChunks(reader) {
    const chunks = [];
    let totalSize = 0;

    // Create a recursive function to read chunks
    function pump() {
      return reader.read().then(({ done, value }) =&amp;gt; {
        if (done) {
          console.log("Stream complete. Total data size:", totalSize, "bytes");
          return chunks;
        }

        // Store the chunk
        chunks.push(value);
        totalSize += value.length;
        console.log("Received chunk of data, size:", value.length, "bytes");

        // Continue reading
        return pump();
      });
    }

    // Start the reading process
    return pump();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me break this function &lt;/p&gt;

&lt;p&gt;The readAllChunks function implements a technique for consuming a ReadableStream completely using recursion.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;chunks: An array that will store all the Uint8Array chunks read from the stream&lt;/li&gt;
&lt;li&gt;totalSize: A counter to track the total number of bytes read&lt;/li&gt;
&lt;li&gt;The pump() function: This inner function implements the recursive reading pattern. It calls reader.read(), which returns a Promise that resolves to an object with done and value properties. Each call reads the next available chunk from the stream&lt;/li&gt;
&lt;li&gt;When done is true, it means the stream has no more data&lt;/li&gt;
&lt;li&gt;Each chunk (in value) is a Uint8Array of binary data
It's added to the chunks array and its length is added to the total
The size of each chunk is logged for monitoring&lt;/li&gt;
&lt;li&gt;return pump(): This recursively calls pump() to read the next chunk
The Promise chain ensures each read completes before the next one starts
This continues until done becomes true&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Return Value: A Promise that resolves to an array of Uint8Array chunks containing all the data from the stream.&lt;/p&gt;

&lt;p&gt;We have written a function to recursively read data by chunks. Let see how we can incorporate this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function to read all chunks from a reader
function readAllChunks(reader) {
    const chunks = [];
    let totalSize = 0;

    // Create a recursive function to read chunks
    function pump() {
      return reader.read().then(({ done, value }) =&amp;gt; {
        if (done) {
          console.log("Stream complete. Total data size:", totalSize, "bytes");
          return chunks;
        }

        // Store the chunk
        chunks.push(value);
        totalSize += value.length;
        console.log("Received chunk of data, size:", value.length, "bytes");

        // Continue reading
        return pump();
      });
    }

    // Start the reading process
    return pump();
  }



/// Usage in our fetch example:
fetch("https://images.pexels.com/photos/1229356/pexels-photo-1229356.jpeg?auto=compress&amp;amp;cs=tinysrgb&amp;amp;w=600")
.then(response =&amp;gt; {
  const reader = response.body.getReader();
  return readAllChunks(reader);
})
.then(chunks =&amp;gt; {
  // Combine all chunks into a single Uint8Array
  const totalLength = chunks.reduce((total, chunk) =&amp;gt; total + chunk.length, 0);
  const combinedData = new Uint8Array(totalLength); // This creates a new Uint8Array with exactly the right size to hold all data

//For each chunk, we copy its data into the combined array and then advance the position. This builds a single contiguous array from all the separate chunks
  let position = 0;
  for (const chunk of chunks) {
    combinedData.set(chunk, position); // Uint8Array.set() copies values from one array to another at a specific position
    position += chunk.length;
  }

  console.log("Complete image data received:", combinedData.length, "bytes");

  // Now you can work with the full image data
  // For example, convert to base64 for display 


  return combinedData;
})
.catch(err =&amp;gt; console.error("Error reading stream:", err));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ouput is: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2los0ll0frti8wy3glp4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2los0ll0frti8wy3glp4.png" alt="Image description" width="573" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see how the data is read chunk by chunk.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is exactly is happening finally here?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;-The fetch() call returns a Promise that resolves to a Response object&lt;br&gt;
From that Response, we extract the body ReadableStream and create a reader. We pass this reader to the readAllChunks function we discussed earlier. This returns a Promise that resolves to an array of Uint8Array chunks when the stream is fully read&lt;/p&gt;

&lt;p&gt;Finally all of your data is read. Now you can process it furthur for your use. We will see next week. &lt;/p&gt;

&lt;p&gt;So what we have understood today?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fetch a resource&lt;/li&gt;
&lt;li&gt;Read all chunks from its stream&lt;/li&gt;
&lt;li&gt;Combine those chunks into a complete dataset&lt;/li&gt;
&lt;li&gt;Process the complete data as needed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thanks. Happy Reading...&lt;br&gt;
Don't forget to share your thoughts....&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>node</category>
    </item>
    <item>
      <title>Quick Cookie Management Tips</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Wed, 29 Jan 2025 14:04:01 +0000</pubDate>
      <link>https://dev.to/indraphoton/quick-cookie-management-tips-3m38</link>
      <guid>https://dev.to/indraphoton/quick-cookie-management-tips-3m38</guid>
      <description>&lt;p&gt;Hey there, fellow developers! 👋 &lt;br&gt;
You know what's funny? I recently hit a roadblock with cookie management in my recent project &lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
    &lt;a href="https://e-commerce-smoky-omega.vercel.app/" rel="noopener noreferrer"&gt;
      e-commerce-smoky-omega.vercel.app
    &lt;/a&gt;
&lt;/div&gt;
, After figuring it out, I thought - "Hey, others might run into this too!" So here I am, sharing what I learned about making cookies work smarter, not harder.&lt;br&gt;
Let me show you how to level up your cookie game!

&lt;h2&gt;
  
  
  What is cookie
&lt;/h2&gt;

&lt;p&gt;A cookie (also known as a web cookie or browser cookie) is a small piece of data a server sends to a user's web browser. The browser may store cookies, create new cookies, modify existing ones, and send them back to the same server with later requests.&lt;br&gt;
-- This is primarily used for session management, personalization and tracking. &lt;/p&gt;

&lt;h2&gt;
  
  
  The Cookie Basics
&lt;/h2&gt;

&lt;p&gt;Think of cookies as small data packets your server sends to users' browsers. They're super handy for things like keeping users logged in or remembering their preferences.&lt;/p&gt;

&lt;h2&gt;
  
  
  Server-Side Cookie Configuration:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const options = {
        httpOnly: true,
        secure: true,
        sameSite: "none"
    }

    return res
    .status(200)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .json(
        new Apiresponse(
            200, 
            {
                user: loggedInUser
            },
            "User logged In Successfully"
        )
    )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is a simple example of how you can send cookies from your server to browser. &lt;br&gt;
Here, I have set two cookies in the response:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;An access token for short-term authentication&lt;/li&gt;
&lt;li&gt;A refresh token for getting new access tokens&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the 'options' I have taken httpOnly, secure, sameSite. These are essential options to set your cookie parameters and security.&lt;br&gt;
These options create secure cookies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;httpOnly: true &lt;em&gt;prevents client-side JavaScript from accessing the cookie, protecting against XSS attacks&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;secure: true &lt;em&gt;ensures cookies are only transmitted over HTTPS&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;sameSite: "none" &lt;em&gt;allows the cookie to be sent in cross-origin requests, which is needed for your frontend-backend communication&lt;/em&gt;&lt;br&gt;
I was actually having problems in this &lt;code&gt;sameSite&lt;/code&gt; parameter&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Client-Side Cookie Handling:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const loginResponse = await axios.post(
    `${base_URL}/api/v1/users/signin`,
    { email, password },
    { withCredentials: true }
);

if (loginResponse.data.data) {
    const userResponse = await axios.get(
        `${base_URL}/api/v1/users/getuser`,
        { 
            withCredentials: true  // This will automatically send the cookies
        }
    );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the client side, when the user is loggedin a cookie is sent from the server to browser and &lt;code&gt;_loginResponse_&lt;/code&gt; become true then I am sending a request to my server to get the cookie from browser using &lt;code&gt;_withCredentials: true_&lt;/code&gt; and make a database query. As a response I get the user data. &lt;/p&gt;

&lt;p&gt;That's simple and easy right?&lt;/p&gt;

&lt;h2&gt;
  
  
  What other options in cookie
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const options = {
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // Expires in 24 hours
    maxAge: 24 * 60 * 60 * 1000, // Alternative way to set expiry in milliseconds
    domain: '.example.com',    // Cookie available on all subdomains
    path: '/',                 // Cookie available for entire domain

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;expires vs maxAge:&lt;/strong&gt; &lt;em&gt;Use either one, not both. maxAge is generally preferred as it's relative to the current time&lt;br&gt;
domain: Be careful with this setting as it affects security. Only set it if you need cross-subdomain access&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;sameSite:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;'strict' is most secure but restricts cross-site requests&lt;br&gt;
'lax' is a good default&lt;br&gt;
'none' requires secure: true&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;'signed'&lt;/strong&gt;: Requires your server to have a secret key configured&lt;br&gt;
partitioned: New feature for privacy, not supported by all browsers yet.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That's all from my side. Hope this helps. Also this is my first article so expects some roasting from you guys. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>security</category>
    </item>
    <item>
      <title>Quick Cookie Management Tips</title>
      <dc:creator>INDRANIL MAITI</dc:creator>
      <pubDate>Wed, 29 Jan 2025 14:04:01 +0000</pubDate>
      <link>https://dev.to/indraphoton/quick-cookie-management-tips-f9f</link>
      <guid>https://dev.to/indraphoton/quick-cookie-management-tips-f9f</guid>
      <description>&lt;p&gt;Hey there, fellow developers! 👋 &lt;br&gt;
You know what's funny? I recently hit a roadblock with cookie management in my recent project &lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
    &lt;a href="https://e-commerce-smoky-omega.vercel.app/" rel="noopener noreferrer"&gt;
      e-commerce-smoky-omega.vercel.app
    &lt;/a&gt;
&lt;/div&gt;
, After figuring it out, I thought - "Hey, others might run into this too!" So here I am, sharing what I learned about making cookies work smarter, not harder.&lt;br&gt;
Let me show you how to level up your cookie game!

&lt;h2&gt;
  
  
  What is cookie
&lt;/h2&gt;

&lt;p&gt;A cookie (also known as a web cookie or browser cookie) is a small piece of data a server sends to a user's web browser. The browser may store cookies, create new cookies, modify existing ones, and send them back to the same server with later requests.&lt;br&gt;
-- This is primarily used for session management, personalization and tracking. &lt;/p&gt;

&lt;h2&gt;
  
  
  The Cookie Basics
&lt;/h2&gt;

&lt;p&gt;Think of cookies as small data packets your server sends to users' browsers. They're super handy for things like keeping users logged in or remembering their preferences.&lt;/p&gt;

&lt;h2&gt;
  
  
  Server-Side Cookie Configuration:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const options = {
        httpOnly: true,
        secure: true,
        sameSite: "none"
    }

    return res
    .status(200)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .json(
        new Apiresponse(
            200, 
            {
                user: loggedInUser
            },
            "User logged In Successfully"
        )
    )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is a simple example of how you can send cookies from your server to browser. &lt;br&gt;
Here, I have set two cookies in the response:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;An access token for short-term authentication&lt;/li&gt;
&lt;li&gt;A refresh token for getting new access tokens&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the 'options' I have taken httpOnly, secure, sameSite. These are essential options to set your cookie parameters and security.&lt;br&gt;
These options create secure cookies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;httpOnly: true &lt;em&gt;prevents client-side JavaScript from accessing the cookie, protecting against XSS attacks&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;secure: true &lt;em&gt;ensures cookies are only transmitted over HTTPS&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;sameSite: "none" &lt;em&gt;allows the cookie to be sent in cross-origin requests, which is needed for your frontend-backend communication&lt;/em&gt;&lt;br&gt;
I was actually having problems in this &lt;code&gt;sameSite&lt;/code&gt; parameter&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Client-Side Cookie Handling:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const loginResponse = await axios.post(
    `${base_URL}/api/v1/users/signin`,
    { email, password },
    { withCredentials: true }
);

if (loginResponse.data.data) {
    const userResponse = await axios.get(
        `${base_URL}/api/v1/users/getuser`,
        { 
            withCredentials: true  // This will automatically send the cookies
        }
    );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the client side, when the user is loggedin a cookie is sent from the server to browser and &lt;code&gt;_loginResponse_&lt;/code&gt; become true then I am sending a request to my server to get the cookie from browser using &lt;code&gt;_withCredentials: true_&lt;/code&gt; and make a database query. As a response I get the user data. &lt;/p&gt;

&lt;p&gt;That's simple and easy right?&lt;/p&gt;

&lt;h2&gt;
  
  
  What other options in cookie
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const options = {
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // Expires in 24 hours
    maxAge: 24 * 60 * 60 * 1000, // Alternative way to set expiry in milliseconds
    domain: '.example.com',    // Cookie available on all subdomains
    path: '/',                 // Cookie available for entire domain

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;expires vs maxAge:&lt;/strong&gt; &lt;em&gt;Use either one, not both. maxAge is generally preferred as it's relative to the current time&lt;br&gt;
domain: Be careful with this setting as it affects security. Only set it if you need cross-subdomain access&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;sameSite:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;'strict' is most secure but restricts cross-site requests&lt;br&gt;
'lax' is a good default&lt;br&gt;
'none' requires secure: true&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;'signed'&lt;/strong&gt;: Requires your server to have a secret key configured&lt;br&gt;
partitioned: New feature for privacy, not supported by all browsers yet.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That's all from my side. Hope this helps. Also this is my first article so expects some roasting from you guys. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>security</category>
    </item>
  </channel>
</rss>
