Cookies vs Sessions: What Is the Difference? Complete Beginner Guide

When you log in to a website, the website usually needs some way to remember that you are authenticated while you move from one page to another.

This is where cookies and sessions become important.

These concepts are fundamental to web development because HTTP itself is generally described as stateless. Without additional mechanisms, the server would not automatically remember that two separate requests came from the same authenticated user.

Simple Definition: A cookie is data stored by the browser and sent with applicable requests, while a session is commonly server-side state associated with a client through a session identifier, often stored in a cookie.

In this guide, you will learn what cookies are, what sessions are, how login systems use them, where data is stored, how cookies differ from sessions, session IDs, expiration, security attributes, PHP and JavaScript examples, common mistakes, and modern authentication considerations.

Why Do Websites Need Cookies and Sessions?

Consider a normal website login.

You enter your username and password and click Login.

The server verifies your credentials.

Now you visit another page.

How does the server know that you are still logged in?

HTTP requests are independent at the protocol level, so applications need additional mechanisms to associate requests with a user or client state.

Login Request
     |
     v
Authentication
     |
     v
Create Session
     |
     v
Session ID
     |
     v
Browser Cookie
     |
     v
Future Requests
     |
     v
Server Finds Session
     |
     v
User Recognized
  

What Is a Cookie?

A cookie is a small piece of data that a website can ask a browser to store.

The browser can then send the cookie back to the appropriate server with subsequent requests, subject to the cookie's attributes and browser rules.

A simplified example is:

Server
  |
  | Set-Cookie
  v
Browser
  |
  | Cookie
  v
Server
  

Cookies are commonly used for:

  • Login sessions
  • Preferences
  • Shopping carts
  • Language settings
  • Analytics
  • Security mechanisms

Example of a Cookie

A server may send a response header such as:

Set-Cookie: session_id=abc123
  

For later requests, the browser may send:

Cookie: session_id=abc123
  

The server can use the session identifier to locate associated server-side state.

What Is a Session?

A session is application state maintained across multiple requests from the same client.

In a common server-side session architecture, the server creates a session record containing information associated with the logged-in user.

For example:

Session ID: abc123

Server-side session:
{
  userId: 101,
  role: "user",
  loggedIn: true
}
  

The browser usually stores only the session identifier rather than the complete session data.

Cookies vs Sessions

Feature Cookies Server-Side Sessions
Typical storage Browser Server or shared session store
Data sent with requests Applicable cookie data can be sent Usually only a session identifier is sent by the client
Typical use Preferences, identifiers, tracking, session IDs Login state and server-maintained user state
Server control over data Limited because data resides on client Server controls session data
Security depends on Cookie attributes, application design, transport security, and data stored Session management, session IDs, storage security, authentication, and application design

Cookie vs Session: The Most Important Idea

Cookies and sessions are not necessarily competing technologies.

They are often used together.

Browser
  |
  | Cookie: session_id=abc123
  v
Web Server
  |
  | Look up abc123
  v
Session Store
  |
  | userId=101
  v
Application
  

This is one of the most common patterns for browser-based authentication.

How Login Sessions Work

Let's look at a simplified login process.

Step 1: User Enters Credentials

POST /login
  

Step 2: Server Verifies Credentials

The server validates the submitted username and password against the application's authentication system.

Step 3: Server Creates a Session

The application creates a random session identifier and stores the associated server-side state.

Step 4: Server Sends Session Cookie

Set-Cookie: session_id=RANDOM_VALUE
  

Step 5: Browser Stores the Cookie

The browser stores the cookie according to the server's instructions and browser policies.

Step 6: Browser Sends the Cookie

Future applicable requests include the session cookie.

Step 7: Server Finds the Session

The server uses the session identifier to retrieve the associated session state.

Cookie
  ↓
Session ID
  ↓
Session Store
  ↓
User ID
  ↓
Authenticated Request
  

What Is a Session ID?

A session ID is an identifier used to associate a client with server-side session state.

It should be difficult for an attacker to guess.

A conceptual example is:

session_id = 9f5d8c7e3a1b...
  

Real session identifiers should be generated using secure randomness provided by the programming platform.

Why Should Session IDs Be Random?

If session identifiers are predictable, an attacker may be able to guess another user's session identifier and impersonate that user.

This type of attack is associated with session hijacking.

Applications should therefore use strong, unpredictable session identifiers and protect them during transport and storage.

What Is Session Hijacking?

Session hijacking is an attack in which an attacker obtains or abuses a valid user's session credentials or session identifier to act as that user.

Potential causes include:

  • Stolen session cookies
  • Insecure transport
  • Cross-site scripting
  • Malware
  • Compromised devices
  • Session management flaws

Applications should protect session identifiers as carefully as authentication credentials.

What Is the Secure Cookie Attribute?

The Secure cookie attribute tells compatible browsers to send the cookie only over secure connections, typically HTTPS.

Set-Cookie: session_id=abc123; Secure
  

For authentication cookies, Secure is an important security control.

What Is the HttpOnly Attribute?

The HttpOnly attribute prevents browser-side JavaScript from directly accessing the cookie through APIs such as document.cookie.

Set-Cookie: session_id=abc123; HttpOnly
  

This can reduce the risk of certain cookie theft scenarios involving client-side scripts.

However, HttpOnly does not prevent cross-site scripting itself and does not make an application immune to XSS attacks.

What Is SameSite?

SameSite is a cookie attribute that controls when browsers send cookies in cross-site contexts.

Common settings include:

  • Strict
  • Lax
  • None

The appropriate setting depends on the application architecture and cross-site requirements.

When SameSite=None is used, browsers require the cookie to also have the Secure attribute.

Secure Session Cookie Example

A typical session cookie might be configured conceptually like:

Set-Cookie:
session_id=RANDOM_VALUE;
Secure;
HttpOnly;
SameSite=Lax
  

The exact settings should match the application's architecture and authentication flow.

What Is a Session Expiration?

Sessions should generally have a defined lifetime or inactivity policy.

For example, an application can expire a session after a period of inactivity.

Login
  ↓
Session Created
  ↓
User Active
  ↓
Session Valid
  ↓
Inactivity
  ↓
Session Expires
  ↓
Login Required
  

Session lifetime should be appropriate to the sensitivity of the application.

Cookie Expiration

Cookies can also have expiration behavior.

A cookie without a persistent expiration can behave as a session cookie, while cookies with an expiration or max-age can persist longer according to browser rules.

For example:

Set-Cookie: preference=dark; Max-Age=3600
  

This example requests a one-hour lifetime.

Session Cookie vs Persistent Cookie

Session Cookie Persistent Cookie
Generally intended to last for a browser session Has an expiration or Max-Age
Often used for temporary state Can persist across browser restarts according to browser rules

Where Are Cookies Stored?

Cookies are stored by the browser according to its internal storage system and policies.

Developers can inspect cookies through browser developer tools.

You may see fields such as:

  • Name
  • Value
  • Domain
  • Path
  • Expires
  • Secure
  • HttpOnly
  • SameSite

Where Are Server-Side Sessions Stored?

Session storage depends on the application.

A session can be stored in:

  • Server memory
  • Files
  • Databases
  • Redis
  • Other shared session stores

For scalable applications running across multiple servers, shared session storage or another architecture that avoids server-local session dependency may be required.

Cookies vs Sessions in PHP

PHP provides built-in session functionality.

A basic example is:

<?php

session_start();

$_SESSION["user_id"] = 101;

echo $_SESSION["user_id"];

?>
  

PHP can use a session cookie to associate the browser with server-side session data.

PHP Cookie Example

You can also create a cookie directly:

<?php

setcookie(
    "theme",
    "dark",
    [
        "expires" => time() + 3600,
        "path" => "/",
        "secure" => true,
        "httponly" => true,
        "samesite" => "Lax"
    ]
);

?>
  

Cookie configuration should match the application's deployment and cross-site requirements.

JavaScript Cookies

JavaScript can read cookies that are not marked HttpOnly through document.cookie.

console.log(document.cookie);
  

Cookies marked HttpOnly are intentionally unavailable to client-side JavaScript.

Client-Side Cookies vs Server-Side Sessions

CLIENT-SIDE COOKIE

Browser
  |
  +-- Stores data
  |
  +-- Sends applicable cookie


SERVER-SIDE SESSION

Browser
  |
  +-- Stores Session ID
  |
  v
Server
  |
  +-- Stores Session Data
  

This difference is important because sensitive application state generally should not simply be trusted because it is stored in a browser cookie.

Can Cookies Store Sensitive Information?

Cookies can contain sensitive information, but developers should think carefully before putting sensitive data directly into client-side storage.

Cookies are sent with applicable requests and can contribute to request size.

Authentication cookies should be configured securely.

For sensitive application state, many applications store only an identifier in the cookie and keep the actual session state server-side.

Can a Cookie Be Modified by the User?

Yes. Data stored on the client should generally be treated as untrusted unless it is protected by an appropriate integrity mechanism and the server validates it.

For example, if a cookie says:

role=admin
  

the server should not simply assume that the user is an administrator.

Authorization must be enforced server-side.

What Is Cookie Tampering?

Cookie tampering means modifying cookie data in an attempt to change application behavior.

Applications should never trust client-controlled values for sensitive authorization decisions without appropriate cryptographic protection and server-side validation.

Cookies and Authentication

Browser-based authentication often uses a secure session cookie.

The flow can look like:

Login
  ↓
Credentials Verified
  ↓
Session Created
  ↓
Session ID Stored in Cookie
  ↓
Browser Sends Cookie
  ↓
Server Retrieves Session
  ↓
User Authenticated
  

This architecture is common because the browser does not need to store the complete server-side session state.

What Is Session Fixation?

Session fixation is an attack in which an attacker causes or predicts a session identifier before the victim authenticates and then attempts to benefit after authentication occurs.

A major defense is to regenerate the session identifier after a successful login or privilege change.

Session Regeneration

After authentication, applications should use a new session identifier rather than continuing to use an identifier that existed before authentication.

In PHP, a common mechanism is:

<?php

session_start();

session_regenerate_id(true);

$_SESSION["user_id"] = 101;

?>
  

This is a simplified example; complete authentication systems need additional security controls.

What Is Session Logout?

Logging out should invalidate the authenticated session according to the application's session management design.

Conceptually:

Logout
  ↓
Invalidate Session
  ↓
Delete / Expire Cookie
  ↓
Future Requests
  ↓
Authentication Required
  

Simply removing a visual login state in the browser is not enough. The server should invalidate the session or authentication credential as appropriate.

Cookies and HTTPS

Authentication cookies should generally be transmitted over HTTPS.

The Secure attribute helps ensure the cookie is sent only through secure connections.

Secure Cookie
      |
      v
HTTPS
      |
      v
Server
  

HTTPS also helps protect the broader communication channel between browser and server.

What Is a Third-Party Cookie?

A third-party cookie is traditionally a cookie associated with a domain different from the site the user is directly visiting, typically arising from embedded third-party content or services.

Browser policies regarding third-party cookies have changed significantly over time and differ by browser and privacy settings.

Developers should therefore check current browser behavior when implementing cross-site functionality.

First-Party vs Third-Party Cookies

First-Party Cookie Third-Party Cookie
Associated with the site the user is visiting Associated with another domain in a cross-site context
Often used for login and preferences Historically used for advertising, analytics, and embedded services

What Is a Cookie Domain?

The Domain attribute determines which hosts can receive a cookie according to browser cookie rules.

For example:

Set-Cookie: theme=dark; Domain=example.com
  

Cookie domain behavior can be subtle, so developers should understand the current browser rules before sharing cookies across subdomains.

What Is the Cookie Path?

The Path attribute controls the URL path scope in which the browser sends the cookie.

For example:

Set-Cookie: session_id=abc123; Path=/
  

Using / means the cookie is available across paths on the relevant host according to cookie rules.

Cookies and CSRF

Cookie-based authentication requires developers to consider Cross-Site Request Forgery (CSRF).

Because browsers can automatically attach cookies to applicable requests, a malicious website may attempt to cause a user's browser to send an authenticated request to another website.

Defenses can include:

  • SameSite cookie configuration
  • CSRF tokens
  • Origin or Referer checks where appropriate
  • Appropriate request design

Cookies and XSS

Cross-Site Scripting (XSS) can allow malicious scripts to execute in a user's browser.

An HttpOnly authentication cookie cannot be directly read by JavaScript, which can reduce one type of cookie theft.

However, XSS can still be extremely serious because malicious code may perform actions through the user's authenticated browser session.

Therefore:

Important: HttpOnly helps protect the cookie from direct JavaScript access, but it does not eliminate the need to prevent XSS.

Session Storage vs Local Storage

Web developers often confuse browser cookies with localStorage and sessionStorage.

Storage Main Characteristic
Cookie Can be automatically sent with matching HTTP requests
localStorage Client-side storage accessible to same-origin JavaScript
sessionStorage Client-side storage associated with a particular browser tab/session context

These mechanisms have different security and persistence characteristics.

Cookie vs localStorage for Authentication

There is no universal answer for every application, but the choice should be based on the application's threat model and architecture.

Authentication cookies can use security attributes such as HttpOnly, Secure, and SameSite.

Data in localStorage is accessible to JavaScript running in the page's origin. This can make sensitive token storage particularly important to evaluate in applications where XSS is a concern.

Sessions in Load-Balanced Applications

Imagine your website runs on three application servers.

             Load Balancer
             /     |     \
            v      v      v
         Server1 Server2 Server3
  

If session data exists only in Server 1's local memory, a later request routed to Server 2 may not find the session.

Common solutions include:

  • Shared session storage
  • Redis-backed sessions
  • Database-backed sessions
  • Other distributed session architectures
  • Stateless authentication designs where appropriate

Sessions and Redis

Redis is frequently used as a fast shared data store for session information.

Browser
   |
Cookie: session_id=abc123
   |
   v
Load Balancer
   |
   +---- Server 1
   |
   +---- Server 2
   |
   +---- Server 3
            |
            v
          Redis
            |
            v
      Session Data
  

This allows multiple application servers to access the same session state when designed appropriately.

Cookie Size and Request Overhead

Cookies are sent with applicable HTTP requests, so putting large amounts of data into cookies increases request overhead.

For this reason, cookies are usually kept relatively small.

Large application data should generally be stored elsewhere, such as server-side storage, databases, or suitable client-side storage mechanisms.

Cookies vs Sessions for Shopping Carts

Shopping carts can use cookies, sessions, databases, or combinations of these technologies.

A simple cart might store a session identifier in a cookie and the actual cart state on the server.

Browser
Cookie:
cart_session=abc123
       |
       v
Server
       |
       v
Cart Data
       |
       +-- Product A
       +-- Product B
  

This approach can keep important business data under server-side control.

Cookies vs Sessions for User Preferences

Simple preferences such as language or a display preference may sometimes be stored directly in a cookie.

For example:

language=en
theme=dark
  

Whether the preference should be stored in a cookie, account profile, or another location depends on the application's requirements.

Cookies vs Sessions in APIs

APIs can use cookie-based sessions, token-based authentication, or other authentication mechanisms.

For a traditional browser application:

Browser
   |
Cookie
   |
   v
Web API
   |
Session Store
  

For other API clients, bearer tokens or other credentials may be used instead.

Session Authentication vs JWT

Server-side sessions and JWT-based authentication are different approaches.

Server-Side Session JWT-Based Authentication
Server maintains session state Token contains claims and is verified by the application
Client commonly stores a session ID Client stores the token according to application design
Server can invalidate a session centrally Revocation requires additional design when tokens are independently valid until expiration
Requires session-state infrastructure for multiple servers Can reduce dependence on centralized request state, depending on the architecture

JWTs are not automatically better than sessions. The correct authentication design depends on the application's requirements and threat model.

Common Cookie Security Mistakes

  1. Not using HTTPS for authentication.
  2. Failing to use Secure for sensitive cookies.
  3. Failing to use HttpOnly where client-side access is unnecessary.
  4. Ignoring SameSite configuration.
  5. Putting sensitive authorization decisions entirely inside client-controlled cookie data.
  6. Using predictable session identifiers.
  7. Failing to regenerate sessions after authentication.
  8. Not expiring or invalidating sessions appropriately.

Common Session Security Mistakes

  1. Using weak session IDs.
  2. Keeping sessions alive indefinitely.
  3. Not invalidating sessions after logout.
  4. Not regenerating session IDs after login.
  5. Storing session data insecurely.
  6. Allowing session IDs to travel over unencrypted connections.
  7. Failing to protect against XSS and CSRF.

Best Practices for Secure Sessions

  • Use HTTPS.
  • Generate unpredictable session identifiers.
  • Use Secure cookies for sensitive sessions.
  • Use HttpOnly for authentication cookies when JavaScript does not need access.
  • Configure SameSite appropriately.
  • Regenerate the session ID after authentication or privilege changes.
  • Expire idle sessions appropriately.
  • Invalidate sessions on logout and account-security events.
  • Protect against XSS and CSRF.
  • Monitor suspicious authentication activity.

Cookies vs Sessions: Easy Memory Trick

Cookie = Client-side storage

Session = Server-side state

Common login pattern = Session ID in a secure cookie + session data on the server

Frequently Asked Questions

```

What is the difference between cookies and sessions?

Cookies are browser-stored data that can be sent with applicable requests, while server-side sessions store application state on the server and commonly use a session ID stored in a cookie to identify that state.

Are cookies stored on the client?

Yes. Cookies are stored by the browser on the client device according to browser policies and cookie attributes.

Are sessions stored on the server?

In the common server-side session model, yes. Session state is stored on a server or shared session store.

Can cookies and sessions be used together?

Yes. A common authentication architecture stores a session identifier in a browser cookie while the associated session data remains server-side.

What is a session ID?

A session ID is an identifier that lets the server associate a request with server-side session state.

What is HttpOnly?

HttpOnly prevents client-side JavaScript from directly accessing a cookie.

What is Secure in a cookie?

The Secure attribute tells compatible browsers to send the cookie only over secure connections such as HTTPS.

What is SameSite?

SameSite controls when a browser sends a cookie in cross-site contexts.

Can a user modify cookies?

Yes. Client-side data should be treated as potentially untrusted. Sensitive authorization decisions must be enforced on the server.

What is session hijacking?

Session hijacking occurs when an attacker obtains or abuses a valid session credential or identifier to act as another user.

What is session fixation?

Session fixation is an attack in which an attacker attempts to make a victim use a session identifier known to the attacker before authentication.

Why regenerate a session ID after login?

Regenerating the session identifier after authentication helps defend against session fixation.

What happens when a user logs out?

A secure application should invalidate the authenticated session or credential and remove or expire the corresponding client-side credential as appropriate.

Are sessions more secure than cookies?

Cookies and sessions are different mechanisms and are often used together. Security depends on implementation, session management, cookie attributes, authentication design, transport security, and application security.

What is the difference between cookies and localStorage?

Cookies can be automatically sent with applicable HTTP requests, while localStorage is client-side storage accessible to same-origin JavaScript and is not automatically included in HTTP requests.

```

Final Thoughts

Cookies and sessions are foundational concepts in web development.

The easiest way to understand their relationship is:

                 LOGIN

                  ↓

            Authentication
                  ↓
             Create Session
                  ↓
       +----------------------+
       | Server               |
       | Session Data         |
       | userId = 101         |
       +----------------------+
                  ↑
                  |
          Session ID
                  |
                  ↓
       +----------------------+
       | Browser Cookie       |
       +----------------------+
                  |
                  ↓
            Future Requests
  

The browser carries the session identifier, while the server uses that identifier to retrieve the associated state.

For developers, the most important security lessons are use HTTPS, protect session identifiers, use appropriate cookie attributes, regenerate sessions after login, enforce authorization server-side, expire sessions appropriately, and protect the application against XSS and CSRF.

CodeWithAV Web Security Tip:

Never assume that a value stored in the browser is trustworthy. The browser is controlled by the user, so authentication and authorization decisions must ultimately be enforced by the server.

Related Articles on CodeWithAV

HTTP vs HTTPS Explained

HTTP Status Codes Every Developer Should Know

What Is an API? Complete Beginner Guide

REST API Explained With Examples

What Is DNS?

Explore More Web Development and Cybersecurity Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.

What Is JSON? Complete Beginner Guide With Examples

If you have worked with APIs, JavaScript, web development, or backend programming, you have probably seen something that looks like this:

{
  "name": "Adarsh",
  "age": 25,
  "skills": ["Python", "JavaScript"]
}
  

This format is called JSON.

JSON is one of the most commonly used formats for representing and exchanging structured data between software systems. It is especially common in web APIs, configuration files, applications, and data-processing workflows.

In this beginner-friendly guide, you will learn what JSON means, how its syntax works, the difference between objects and arrays, nested JSON, data types, JSON in APIs, common mistakes, JSON vs XML, and practical examples.

Simple Definition: JSON stands for JavaScript Object Notation. It is a text-based format used to represent structured data in a way that is relatively easy for people and software to read and process.



What Does JSON Stand For?

JSON stands for JavaScript Object Notation.

Despite its name, JSON is not limited to JavaScript. JSON data can be processed by many programming languages, including Python, Java, C#, PHP, Go, Ruby, and many others.

Why Is JSON So Popular?

JSON is popular because it is:

  • Easy for humans to read
  • Easy for programs to parse
  • Compact compared with many older data formats
  • Widely supported by programming languages
  • Commonly used by web APIs
  • Suitable for nested and structured information

What Does JSON Look Like?

Here is a simple JSON object:

{
  "name": "Rahul",
  "age": 22,
  "city": "Prayagraj"
}
  

This data contains three properties:

  • name → Rahul
  • age → 22
  • city → Prayagraj

JSON Object

A JSON object is enclosed in curly braces:

{
  "key": "value"
}
  

An object contains one or more key-value pairs.

For example:

{
  "username": "adarsh",
  "role": "developer"
}
  

Here:

  • username is the key.
  • adarsh is the value.
  • role is another key.
  • developer is its value.

What Is a JSON Key?

A key identifies a piece of data inside a JSON object.

For example:

{
  "email": "user@example.com"
}
  

email is the key.

In standard JSON syntax, object member names are written as strings using double quotation marks.

What Is a JSON Value?

A value is the data associated with a key.

JSON supports several important value types.

JSON Data Types

The main JSON value types are:

  • String
  • Number
  • Object
  • Array
  • Boolean
  • Null

1. String

A string contains text and is enclosed in double quotes.

{
  "name": "Adarsh"
}
  

2. Number

JSON supports numeric values without quotes.

{
  "age": 25,
  "price": 1499.50
}
  

3. Boolean

Boolean values are either true or false.

{
  "isStudent": true,
  "isBlocked": false
}
  

4. Null

null represents the absence of a value.

{
  "middleName": null
}
  

5. Array

An array contains an ordered collection of values and is enclosed in square brackets.

{
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ]
}
  

6. Object

An object can itself be used as a value inside another object.

{
  "user": {
    "name": "Adarsh",
    "role": "Developer"
  }
}
  

JSON Objects vs JSON Arrays

Two of the most important JSON structures are objects and arrays.

JSON Object

Objects use curly braces:

{
  "name": "Adarsh",
  "age": 25
}
  

JSON Array

Arrays use square brackets:

[
  "Python",
  "JavaScript",
  "SQL"
]
  

An array can also contain objects.

[
  {
    "id": 1,
    "name": "Rahul"
  },
  {
    "id": 2,
    "name": "Anita"
  }
]
  

Nested JSON

JSON can represent complex structures by placing objects and arrays inside other objects and arrays.

Example:

{
  "name": "Adarsh",
  "contact": {
    "email": "user@example.com",
    "phone": "9876543210"
  },
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ]
}
  

Here, contact contains another JSON object and skills contains an array.

JSON Syntax Rules

Although JSON is simple, its syntax is strict.

Rule 1: Use Double Quotes for Object Keys

Correct:

{
  "name": "Adarsh"
}
  

Using an unquoted key is not valid standard JSON:

{
  name: "Adarsh"
}
  

Rule 2: Separate Properties With Commas

Correct:

{
  "name": "Adarsh",
  "age": 25
}
  

Rule 3: Do Not Add a Trailing Comma

This is invalid standard JSON:

{
  "name": "Adarsh",
  "age": 25,
}
  

The comma after 25 should be removed.

Rule 4: Strings Use Double Quotes

Standard JSON uses double quotation marks for strings.

Rule 5: Boolean Values Are Lowercase

Use:

true
false
  

Not:

True
False
  

Rule 6: Null Is Lowercase

null
  

Complete JSON Example

{
  "id": 101,
  "name": "Adarsh Verma",
  "age": 25,
  "isStudent": true,
  "email": "user@example.com",
  "phone": null,
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ],
  "address": {
    "city": "Prayagraj",
    "state": "Uttar Pradesh",
    "country": "India"
  }
}
  

This example demonstrates numbers, strings, booleans, null, arrays, and nested objects.

JSON in REST APIs

JSON is commonly used as the format for request and response bodies in REST APIs.

For example, a client might send:

POST /api/users
Content-Type: application/json
  

Request body:

{
  "name": "Adarsh",
  "email": "user@example.com"
}
  

The server could return:

{
  "id": 101,
  "name": "Adarsh",
  "email": "user@example.com",
  "created": true
}
  

JSON Request vs JSON Response

JSON Request JSON Response
Sent by client Returned by server
Contains input or requested data Contains result or requested information
Common with POST/PUT/PATCH Common for successful API operations

Content-Type: application/json

When an HTTP request contains a JSON body, the client commonly indicates the format using:

Content-Type: application/json
  

This helps the server understand how the request body should be interpreted.

JSON and JavaScript

JSON looks similar to JavaScript object syntax, but JSON and JavaScript objects are not exactly the same thing.

For example, JavaScript can contain:

const user = {
  name: "Adarsh",
  age: 25
};
  

Valid JSON would be represented as:

{
  "name": "Adarsh",
  "age": 25
}
  

JSON is a data interchange format, while a JavaScript object is an in-memory language value.

JSON.parse()

JavaScript provides JSON.parse() to convert a JSON string into a JavaScript value.

const jsonText = '{"name":"Adarsh","age":25}';

const user = JSON.parse(jsonText);

console.log(user.name);
  

After parsing, the application can access the data as a JavaScript object.

JSON.stringify()

JavaScript provides JSON.stringify() to convert a JavaScript value into a JSON string.

const user = {
  name: "Adarsh",
  age: 25
};

const jsonText = JSON.stringify(user);

console.log(jsonText);
  

This is commonly useful when preparing data for transmission or storage.

JSON With Fetch API

Modern browsers provide the Fetch API for HTTP communication.

For example:

fetch("/api/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
  

The response.json() method reads the response body and parses JSON.

JSON in Python

Python also provides built-in JSON support through its json module.

Example:

import json

data = '{"name": "Adarsh", "age": 25}'

user = json.loads(data)

print(user["name"])
  

Python can also convert dictionaries into JSON text.

import json

user = {
    "name": "Adarsh",
    "age": 25
}

json_text = json.dumps(user)

print(json_text)
  

JSON in PHP

PHP provides functions such as json_encode() and json_decode().

Example:

<?php

$user = [
    "name" => "Adarsh",
    "age" => 25
];

echo json_encode($user);

?>
  

This can produce JSON such as:

{"name":"Adarsh","age":25}
  

JSON vs XML

Before JSON became widely popular in web development, XML was commonly used for structured data exchange.

Compare the same information in both formats.

JSON

{
  "name": "Adarsh",
  "age": 25
}
  

XML

<user>
  <name>Adarsh</name>
  <age>25</age>
</user>
  

Both can represent structured data. The choice depends on application requirements, existing systems, tooling, and API design.

JSON vs XML Comparison

JSON XML
Compact syntax Tag-based syntax
Common in modern web APIs Widely used in many existing enterprise and document-oriented systems
Native data structures for objects and arrays Uses elements and attributes
Generally straightforward for web developers Can support rich document structures and established XML technologies

Can JSON Store Functions?

No. Standard JSON does not have a function data type.

For example, this JavaScript object contains a function:

{
  name: "Adarsh",
  greet: function() {
    console.log("Hello");
  }
}
  

This cannot be represented as standard JSON in the same way.

Can JSON Store Dates?

JSON does not have a dedicated date type.

Applications commonly represent dates as strings, often using an agreed format such as an ISO-style timestamp.

{
  "createdAt": "2026-09-25T10:30:00Z"
}
  

The receiving application must interpret the string according to the API's documented rules.

Common JSON Mistakes

1. Using Single Quotes

This is not valid standard JSON:

{'name': 'Adarsh'}
  

Use double quotes:

{"name": "Adarsh"}
  

2. Trailing Commas

Do not add a comma after the final property or array element.

3. Incorrect Boolean Values

Use:

true
false
  

4. Missing Quotes Around Keys

Standard JSON requires object member names to be strings.

5. Missing Commas

Separate neighboring object properties or array values correctly.

6. Invalid Escape Sequences

Special characters inside strings must follow JSON's escaping rules.

How to Validate JSON

Because JSON syntax is strict, even a small formatting mistake can make a document invalid.

You can validate JSON using:

  • Code editors
  • Browser developer tools
  • Programming-language JSON parsers
  • Dedicated JSON validation tools
  • API testing tools

For applications, using the parser provided by your programming environment is often a reliable way to detect malformed JSON.

JSON Schema

JSON itself describes the structure of data, but it does not by itself define all the business rules an application might require.

JSON Schema is a separate specification that can describe expected JSON structure and constraints.

For example, a schema could specify that:

  • name must be a string
  • age must be a number
  • email should follow a defined format
  • id is required

This can help teams validate API payloads and communicate data contracts.

JSON and Databases

Applications frequently convert database records into JSON before returning them through APIs.

Database
   |
   v
Backend
   |
Convert Data
   |
   v
JSON Response
   |
   v
Frontend
  

A backend might query a relational or NoSQL database, transform the result, and return JSON to the frontend.

JSON in Full-Stack Development

JSON is especially important in full-stack applications.

A typical flow could be:

React / Frontend
       |
       | JSON Request
       v
REST API
       |
       v
Node.js / PHP / Python / Java
       |
       v
Database
       |
       v
JSON Response
       |
       v
Frontend UI
  

This is why understanding JSON is extremely useful for web developers.

JSON Security Considerations

JSON is a data format, not a security mechanism.

An API that uses JSON still requires appropriate security controls.

Developers should consider:

  • Input validation
  • Authentication
  • Authorization
  • HTTPS
  • Output handling
  • Payload size limits
  • Error handling
  • Protection of sensitive information

Never assume that JSON received from a client is trustworthy simply because it follows valid JSON syntax.

JSON and API Design

Good API design requires more than choosing JSON.

A well-designed API should clearly define:

  • Available endpoints
  • Request structure
  • Response structure
  • Authentication requirements
  • Validation rules
  • Error responses
  • Pagination behavior
  • Rate limits

Consistency is particularly important when many clients depend on the API.

Practical JSON Example: Product API

Suppose an online store returns a product:

{
  "id": 501,
  "name": "Mechanical Keyboard",
  "price": 2499,
  "currency": "INR",
  "available": true,
  "tags": [
    "keyboard",
    "mechanical",
    "gaming"
  ]
}
  

This response can easily be consumed by a website or mobile application.

Practical JSON Example: Blog API

{
  "id": 10,
  "title": "What Is JSON?",
  "author": {
    "id": 5,
    "name": "Adarsh"
  },
  "tags": [
    "JSON",
    "API",
    "Programming"
  ],
  "published": true
}
  

Notice how JSON can represent relationships and nested information in a readable structure.

How to Learn JSON

Beginners can learn JSON quickly by practicing the following:

  1. Learn key-value pairs.
  2. Learn JSON objects.
  3. Learn JSON arrays.
  4. Practice strings, numbers, booleans, and null.
  5. Practice nested objects.
  6. Practice arrays of objects.
  7. Read real API responses.
  8. Use JSON with JavaScript or Python.
  9. Build a small REST API.
  10. Validate and test JSON payloads.

JSON Practice Example

Try creating JSON for a student with:

  • Student ID
  • Name
  • Email
  • Course
  • Three subjects
  • Address
  • Whether the student is active

A possible answer is:

{
  "studentId": 101,
  "name": "Rahul",
  "email": "rahul@example.com",
  "course": "MCA",
  "subjects": [
    "DBMS",
    "Computer Networks",
    "Programming"
  ],
  "address": {
    "city": "Prayagraj",
    "state": "Uttar Pradesh"
  },
  "active": true
}
  

Frequently Asked Questions

```

What is JSON in simple words?

JSON is a text-based format used to represent structured data so that software systems can exchange and process information.

What does JSON stand for?

JSON stands for JavaScript Object Notation.

Is JSON a programming language?

No. JSON is a data interchange format.

Is JSON only used with JavaScript?

No. Many programming languages can parse and generate JSON.

What are the main JSON data types?

JSON supports strings, numbers, objects, arrays, booleans, and null.

What is the difference between JSON object and JSON array?

A JSON object contains key-value pairs and uses curly braces, while an array contains an ordered collection of values and uses square brackets.

Why is JSON used in APIs?

JSON provides a widely supported and relatively compact way to represent structured request and response data.

Can JSON contain functions?

No. Standard JSON does not have a function data type.

Can JSON contain dates?

JSON has no dedicated date type. Applications commonly represent dates as strings using an agreed format.

What is JSON.parse()?

In JavaScript, JSON.parse() converts a JSON string into a JavaScript value.

What is JSON.stringify()?

In JavaScript, JSON.stringify() converts a JavaScript value into a JSON string.

Is JSON secure?

JSON is only a data format. Security depends on how the application validates, authenticates, authorizes, transports, stores, and processes the data.

```

Final Thoughts

JSON is one of the most important formats to understand if you want to learn web development, APIs, backend programming, mobile development, or full-stack development.

The core concepts are simple: objects, arrays, keys, values, strings, numbers, booleans, null, and nested structures.

Once you understand those concepts, you will be able to read API responses, send data to backend servers, work with JavaScript's JSON functions, and communicate between different software systems much more comfortably.

CodeWithAV JSON Learning Path:

JSON Syntax → Objects → Arrays → Data Types → Nested JSON → API Requests → API Responses → JSON.parse() → JSON.stringify() → JSON Schema → Real API Projects.

Related Articles on CodeWithAV

What Is an API? Complete Beginner Guide

REST API Explained With Examples

What Is Cloud Computing?

What Is the Internet and How Does It Work?

Explore More Web Development Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.

How to Build an AI Agent from Scratch in 2026: Beginner Guide

How to Build an AI Agent from Scratch

AI agents are becoming an important part of modern software development.

An ordinary chatbot can answer a question, but an AI agent can go further. Depending on how it is designed, an agent can decide what steps are needed, use tools, inspect results, maintain context, and continue working until a defined goal is reached.

This makes agents useful for tasks such as:

  • Research assistance
  • Customer support
  • Software development
  • Data analysis
  • Document processing
  • Workflow automation
  • IT operations
  • Personal productivity

In this beginner-friendly guide, we will build the concepts step by step and create a simple agent architecture using JavaScript and Node.js.

Important: Agent frameworks, model names, SDKs, tool interfaces and API features change quickly. The architecture in this article is intentionally general. Always check the current official documentation for the AI provider you choose.

What Is an AI Agent?

An AI agent is a software system that uses an AI model to interpret a task, decide on actions, use available tools or information, and work through one or more steps toward a goal.

A simple agent can be represented as:

User Goal
    ↓
AI Model
    ↓
Decision
    ↓
Tool
    ↓
Tool Result
    ↓
AI Model
    ↓
Next Decision
    ↓
Final Result

Anthropic describes agents as systems that can plan and operate over multiple turns while using tools and environmental feedback, with stopping conditions and human checkpoints where appropriate.

Chatbot vs AI Agent

Chatbot AI Agent
Usually responds to a user message. Can work through multiple steps toward a goal.
May not have tools. Can use tools provided by the application.
Often follows a simpler request-response flow. May use a loop of decisions, actions and results.
Memory may be limited to conversation context. Can use application-managed short- or long-term state.

The boundary is not always strict. Some systems called “agents” are really structured workflows, while others are more autonomous. The architecture should match the actual problem rather than the label.

What Are the Main Components of an AI Agent?

A practical agent can contain several components.

1. AI Model

The model interprets instructions and produces decisions or responses.

2. Instructions

Instructions define the agent's role, goals, constraints and expected behavior.

3. Tools

Tools allow the agent to perform actions outside the model itself.

Examples include:

  • Web search
  • Database queries
  • Calculator
  • File access
  • Weather lookup
  • Email systems
  • Calendar systems
  • Application APIs
  • Code execution

4. Memory or State

State allows the application to preserve information across steps or conversations where appropriate.

5. Agent Loop

The loop allows the application to continue processing tool calls and results until it reaches a final response or another stopping condition.

6. Guardrails

Guardrails restrict unsafe, unauthorized or unintended behavior.

Agent Architecture

A simple agent architecture can look like this:

                   ┌─────────────┐
                   │   User      │
                   └──────┬──────┘
                          ↓
                   ┌─────────────┐
                   │ AI Agent    │
                   │   Model     │
                   └──────┬──────┘
                          ↓
                 ┌───────────────┐
                 │ Decision /    │
                 │ Tool Selection│
                 └───────┬───────┘
                         ↓
        ┌────────────────────────────────┐
        │            Tools               │
        │                                │
        │ Search | DB | Files | APIs     │
        └────────────────┬───────────────┘
                         ↓
                  Tool Result
                         ↓
                    AI Agent
                         ↓
                    Final Answer

Agent vs Traditional Automation

A traditional automation system generally follows a predefined sequence.

For example:

Step 1 → Step 2 → Step 3 → Step 4

An agent can choose between available actions based on the current task and intermediate results:

Goal
 ↓
Observe
 ↓
Decide
 ↓
Act
 ↓
Observe Result
 ↓
Decide Again
 ↓
Stop

This flexibility is useful for open-ended tasks where you cannot reliably hardcode the number of steps in advance. Anthropic identifies this type of open-ended problem as one area where agents can be appropriate.

What Should You Know Before Building an AI Agent?

You do not need to be an AI researcher.

Start by understanding:

  • Basic programming
  • Functions
  • HTTP requests
  • JSON
  • REST APIs
  • Authentication
  • Environment variables
  • Error handling
  • Basic application security

Knowledge of JavaScript or Python is especially useful.

Technologies for Our Example

We will use:

  • Node.js
  • JavaScript
  • Express.js
  • An AI API
  • Simple application-defined tools

Later, you can replace the custom loop with a specialized agent SDK. OpenAI currently provides an Agents SDK for JavaScript/TypeScript and Python applications.

Project Structure

ai-agent/
│
├── server.js
├── agent.js
├── tools.js
├── package.json
├── .env
│
└── public/
    ├── index.html
    ├── style.css
    └── script.js

Step 1: Create the Project

mkdir ai-agent
cd ai-agent
npm init -y

Step 2: Install Dependencies

npm install express dotenv

You can add the SDK or HTTP client required by your chosen AI provider after selecting the provider.

Step 3: Create Environment Variables

Create a .env file:

AI_API_KEY=your_secret_api_key

Never publish this file to GitHub.

Create a .gitignore file:

node_modules/
.env

Step 4: Define a Tool

Let's start with a simple calculator tool.

Create tools.js:

function calculator(a, b, operation) {

    if (typeof a !== "number" || typeof b !== "number") {
        throw new Error("Numbers are required.");
    }

    switch (operation) {

        case "add":
            return a + b;

        case "subtract":
            return a - b;

        case "multiply":
            return a * b;

        case "divide":

            if (b === 0) {
                throw new Error("Cannot divide by zero.");
            }

            return a / b;

        default:
            throw new Error("Unsupported operation.");
    }
}

module.exports = {
    calculator
};

This is a normal application function. The AI does not execute arbitrary code itself; your application decides which tools exist and how they can be called.

Step 5: Define the Agent

Create agent.js:

const { calculator } = require("./tools");

const tools = {
    calculator
};

async function runAgent(userGoal) {

    const state = {
        goal: userGoal,
        history: [],
        maxSteps: 5
    };

    for (let step = 0; step < state.maxSteps; step++) {

        const decision = await askModel(
            state.goal,
            state.history
        );

        if (decision.type === "final") {
            return decision.answer;
        }

        if (decision.type === "tool") {

            const tool = tools[decision.name];

            if (!tool) {
                throw new Error("Unknown tool requested.");
            }

            const result = await tool(...decision.arguments);

            state.history.push({
                type: "tool_result",
                tool: decision.name,
                result
            });

            continue;
        }

        throw new Error("Invalid agent decision.");
    }

    throw new Error("Agent reached maximum step limit.");
}

async function askModel(goal, history) {

    /*
       Replace this function with the AI-provider
       API or SDK call used by your application.
    */

    return {
        type: "final",
        answer: `Agent received: ${goal}`
    };
}

module.exports = {
    runAgent
};

This example demonstrates the most important concept: the agent repeatedly asks the model what to do, executes approved tools, records the result, and continues until it reaches a stopping condition.

Understanding the Agent Loop

The heart of an agent is often a loop.

while (!finished) {

    observe();

    decision = model();

    if (decision requires tool) {
        result = runTool();
        record(result);
    }

    if (decision is final answer) {
        finished = true;
    }
}

The loop should always have a reliable stopping mechanism.

For example:

  • Maximum number of steps
  • Maximum execution time
  • Budget limit
  • Successful completion
  • Human approval requirement
  • Error threshold

Anthropic specifically recommends stopping conditions and appropriate guardrails for agentic systems because autonomy can increase cost and compound errors.

What Is Tool Calling?

Tool calling is a mechanism through which an AI model can request that your application execute a predefined function or external capability.

Suppose the user asks:

Calculate 25 × 16.

The model may determine that the calculator tool is appropriate.

Your application can then execute something conceptually similar to:

{
    "tool": "calculator",
    "arguments": [25, 16, "multiply"]
}

Your code performs the calculation and sends the result back into the agent loop.

Why Tools Matter

An AI model by itself mainly generates or analyzes information. Tools allow the surrounding application to interact with the real world or authoritative application data.

For example:

Tool Possible Function
Calculator Perform calculations
Search Retrieve information
Database Read authorized application data
Email Draft or send messages, subject to permissions
Calendar Create or inspect scheduled items, subject to permissions
File system Read or modify approved files

Build Tools With Clear Contracts

Every tool should have a clear contract.

A tool definition should specify:

  • Tool name
  • Purpose
  • Accepted arguments
  • Argument types
  • Validation rules
  • Permissions
  • Expected output
  • Failure behavior

Good tool definitions make it easier for an AI system to use tools correctly.

Adding a Search Tool

A search tool might look conceptually like this:

async function searchWeb(query) {

    if (typeof query !== "string" || !query.trim()) {
        throw new Error("Search query is required.");
    }

    // Call your selected search provider here.

    return {
        results: []
    };
}

The actual implementation depends on which search service you choose.

Adding Memory

Memory allows an agent to use information from previous interactions.

There are several possible forms of memory.

Short-Term Memory

Conversation history for the current task or session.

Long-Term Memory

Information intentionally stored across sessions, such as user preferences or application state.

External Knowledge

Documents, databases and other knowledge sources retrieved when needed.

These concepts should not be mixed together blindly. Decide which information actually needs to persist.

Simple Agent Memory Example

const memory = [];

memory.push({
    role: "user",
    content: "My project uses React."
});

memory.push({
    role: "assistant",
    content: "I will keep the React stack in mind."
});

For a real application, conversation state would usually be stored in a database or another suitable state-management system.

Adding a Database

For a production agent, a database can store:

  • Users
  • Sessions
  • Tasks
  • Messages
  • Tool calls
  • Results
  • Usage information
  • Agent configuration

A simple relational model could look like:

users
-----
id
email
created_at

sessions
--------
id
user_id
created_at

messages
--------
id
session_id
role
content
created_at

tool_calls
----------
id
session_id
tool_name
arguments
result
created_at

Adding Multiple Tools

An agent becomes more capable when it has access to multiple carefully designed tools.

For example:

const tools = {

    calculator,

    searchWeb,

    getUserProfile,

    getProductInfo,

    createTask

};

The important point is that tools should expose only the actions the agent actually needs.

Do Not Give an Agent Unlimited Access

This is one of the most important principles in agent development.

Do not give an experimental agent unrestricted access to:

  • Production databases
  • Operating-system commands
  • Financial systems
  • User accounts
  • Private documents
  • Administrative controls
  • Destructive operations

Use least-privilege permissions and controlled environments.

Human Approval

Some actions should require human approval before execution.

Examples include:

  • Sending an important email
  • Deleting data
  • Publishing content
  • Changing production configuration
  • Making purchases
  • Performing security-sensitive operations

A simple approval flow could be:

Agent decides
      ↓
Sensitive action detected
      ↓
Pause
      ↓
Ask human
      ↓
Approve / Reject
      ↓
Continue / Stop

Current OpenAI agent documentation also includes guardrails and human-review concepts as part of agent workflows.

Agent Guardrails

Guardrails are rules that control what an agent can and cannot do.

Examples include:

  • Maximum number of tool calls
  • Maximum token or usage budget
  • Allowed domains
  • Allowed files
  • Allowed database operations
  • Authentication requirements
  • Human approval requirements
  • Input and output validation

Sandboxing

When an agent needs to interact with files, code or commands, a sandbox can reduce the impact of mistakes.

A sandbox can restrict:

  • Which files are accessible
  • Which commands can execute
  • Network access
  • Available computing resources
  • Execution time

OpenAI currently documents sandbox-based agent execution as one option for controlled agent workflows.

Example: AI Research Agent

Suppose you want to build a research assistant.

The goal is:

"Research the basics of cloud computing and create a summary."

The agent might follow:

  1. Understand the task.
  2. Identify useful research questions.
  3. Search for relevant information.
  4. Collect results.
  5. Evaluate the gathered information.
  6. Generate a structured summary.
  7. Return the final answer.

The exact sequence can change depending on the information discovered during execution.

Example: Coding Agent

A coding agent might receive:

"Find why the login function is failing and propose a fix."

The agent might:

  1. Inspect relevant files.
  2. Identify the authentication code.
  3. Analyze the error.
  4. Inspect related configuration.
  5. Propose a fix.
  6. Run tests in a controlled environment.
  7. Report the result.

Modern agent tooling can combine models, tools, files, code execution and controlled environments for these kinds of workflows.

Single-Agent vs Multi-Agent Systems

You do not necessarily need multiple agents.

Single-Agent

One agent has access to several tools.

User
 ↓
One Agent
 ↓
Multiple Tools

Multi-Agent

Multiple specialized agents work together.

               Coordinator
               /    |    \
              /     |     \
       Researcher  Coder  Reviewer

A multi-agent system can be useful when tasks have clearly separated responsibilities, but it also introduces more coordination complexity.

Anthropic recommends matching the complexity of the architecture to the value and requirements of the problem instead of automatically choosing complex orchestration.

Agent Workflow vs Agent

Not every AI workflow needs autonomous decision-making.

For example:

Input
 ↓
Summarize
 ↓
Translate
 ↓
Format
 ↓
Output

This is a predictable workflow and may not require a full agent loop.

An agent becomes more appropriate when the required steps depend significantly on the current task and intermediate results.

How to Connect an AI Provider

The provider-specific section normally contains:

  1. API authentication.
  2. Model selection.
  3. Instructions.
  4. Conversation or task context.
  5. Tool definitions.
  6. Tool-call handling.
  7. Result processing.

Current OpenAI documentation, for example, offers a code-first Agents SDK for JavaScript/TypeScript and Python that handles agent runs and can be extended with tools and specialist agents.

Using an Agent SDK

Once you understand the underlying architecture, an SDK can reduce the amount of boilerplate code you need to write.

For example, OpenAI's current Agents SDK quickstart uses concepts such as:

Agent
   ↓
Run
   ↓
Tools
   ↓
Additional steps
   ↓
Final result

Other AI platforms also provide their own frameworks, SDKs or APIs. The concepts remain similar even though the syntax differs.

What Is Context Management?

Context management means deciding what information the model receives at each stage of the task.

Sending everything all the time can increase cost and reduce clarity.

Useful context may include:

  • Current task
  • Relevant conversation history
  • Tool results
  • Important user preferences
  • Retrieved documents
  • System instructions

Remove irrelevant context when possible.

What Is RAG in an Agent?

RAG stands for Retrieval-Augmented Generation.

An agent can use a retrieval tool to find relevant information before generating an answer.

User Question
     ↓
Agent
     ↓
Retrieve Relevant Information
     ↓
Agent
     ↓
Answer

This approach is useful for internal knowledge bases, document assistants, technical documentation and other domain-specific systems.

Agent Logging

Agent systems can be difficult to debug if you only store the final answer.

Consider logging:

  • Task ID
  • Session ID
  • Model used
  • Tool selected
  • Tool arguments
  • Tool result status
  • Execution time
  • Errors
  • Final result

Do not log secrets or sensitive information unnecessarily.

Agent Observability

Observability helps you understand what happened during an agent run.

You may want to measure:

  • Number of steps
  • Tool-call frequency
  • Latency
  • Error rate
  • API usage
  • Cost
  • Task-success rate

OpenAI currently documents tracing and observability as part of its agent development tooling, while its agent guidance also distinguishes between different runtime choices depending on who controls orchestration and state.

Testing AI Agents

Testing an agent is more complicated than testing a normal function because the model may choose different paths.

Create test cases for:

  • Normal requests
  • Ambiguous requests
  • Missing information
  • Tool failures
  • Invalid arguments
  • Network failures
  • Repeated tasks
  • Long tasks
  • Unauthorized actions

Also test whether the agent stops correctly.

Agent Evaluation

An agent may produce different outputs for similar tasks, so you should measure behavior rather than judging the system only by individual examples.

Useful evaluation criteria include:

  • Task completion
  • Correctness
  • Tool selection
  • Policy compliance
  • Response quality
  • Latency
  • Cost

Anthropic's 2026 guidance on agent evaluations emphasizes that multi-step tool use and changing state make agent evaluation more difficult and makes systematic evaluation important before production deployment.

Common AI Agent Mistakes

  • Giving the agent too many tools.
  • Giving tools excessive permissions.
  • Allowing unlimited execution loops.
  • Not validating tool arguments.
  • Not handling tool failures.
  • Ignoring cost limits.
  • Exposing API credentials.
  • Skipping human approval for sensitive actions.
  • Testing only successful scenarios.
  • Using an agent where a simple workflow would be enough.

How to Make an Agent More Reliable

Reliability comes from combining the model with strong software engineering.

  • Use clear instructions.
  • Keep tool interfaces simple.
  • Validate all tool inputs.
  • Use explicit stopping conditions.
  • Limit permissions.
  • Require approval for sensitive actions.
  • Record important execution events.
  • Evaluate realistic scenarios.
  • Use retries carefully.
  • Design for failure.

AI Agent Cost Control

Agents can make multiple model and tool calls for a single user task.

That means costs can grow faster than with a simple single-response application.

Cost-control strategies include:

  • Limit maximum agent steps.
  • Use smaller models when suitable.
  • Reduce unnecessary context.
  • Cache suitable results.
  • Set per-user quotas.
  • Monitor tool-call frequency.
  • Stop loops that are not making progress.

Security Checklist for AI Agents

  • Keep API keys on the server.
  • Use environment variables or secret management.
  • Authenticate users where appropriate.
  • Authorize every sensitive tool operation.
  • Validate tool arguments.
  • Use least-privilege permissions.
  • Set execution limits.
  • Use sandboxing for risky operations.
  • Monitor abnormal behavior.
  • Protect user data.

Beginner AI Agent Project Ideas

1. AI Study Agent

Create an agent that explains concepts, generates practice questions and organizes a study session.

2. Research Agent

Build an agent that searches selected sources and creates a structured research summary.

3. Coding Agent

Build a controlled assistant that reviews code, explains errors and suggests fixes.

4. Document Agent

Create an agent that retrieves relevant information from a collection of documents.

5. Customer Support Agent

Create an assistant that uses a knowledge base and predefined support tools.

6. Productivity Agent

Build an assistant that works with tasks, notes and calendars through authorized tools.

7. Server Monitoring Agent

Create a controlled monitoring assistant that reads system metrics and alerts an operator about predefined conditions. Avoid giving it unrestricted production access.

AI Agent Learning Roadmap

  1. Learn programming fundamentals.
  2. Understand APIs.
  3. Learn JSON and HTTP.
  4. Build a basic chatbot.
  5. Learn tool calling.
  6. Build one simple agent loop.
  7. Add memory or state.
  8. Add multiple tools.
  9. Add validation and guardrails.
  10. Add authentication.
  11. Add monitoring and evaluation.
  12. Deploy in a controlled environment.

Should Beginners Use an AI Agent Framework?

Frameworks and SDKs can save development time, but beginners should understand the underlying architecture first.

Once you understand:

Model
+
Instructions
+
Tools
+
State
+
Agent Loop
+
Guardrails

it becomes much easier to understand what an agent framework is doing for you.

When Should You Not Build an AI Agent?

Do not use an autonomous agent just because the technology is available.

A normal application or workflow may be better when:

  • The steps are completely predictable.
  • The task has strict deterministic rules.
  • Every action needs exact reproducibility.
  • The cost of a wrong action is very high.
  • The task can be implemented more simply without an agent loop.

A simpler system is often easier to test, secure and maintain.

Final Thoughts

AI agents are not simply smarter chatbots. The important difference is the ability of an agentic system to work through tasks using models, tools, context and controlled execution loops.

You can start with a very small system:

One Model
+
One Tool
+
One Goal
+
Maximum 3–5 Steps

Once that works, gradually add memory, additional tools, retrieval, authentication, monitoring, human approval and better evaluations.

The most important lesson is to build agents as controlled software systems. Give them clear goals, narrowly defined tools, limited permissions and explicit stopping conditions.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.

How to Build an AI Chatbot from Scratch: Beginner Guide with HTML, JavaScript & Node.js

How to Build an AI Chatbot from Scratch

AI chatbots are among the most practical applications of artificial intelligence. They can answer questions, explain concepts, summarize information, assist customers, help students, and automate conversations.

The good news is that you do not need to train a large AI model from scratch to build a useful chatbot. A common approach is to create a web interface, connect it to your backend, and let the backend communicate with an AI API.

In this tutorial, we will understand the architecture, required technologies, backend flow, frontend interface, security considerations, conversation history, testing, and deployment.

Note: AI APIs and model names change frequently. The architecture in this tutorial is intentionally provider-neutral. Replace the provider-specific API call with the current SDK or API documented by the provider you choose.

What Is an AI Chatbot?

An AI chatbot is a software application that communicates with users using natural language and uses an AI system to generate or select responses.

A basic chatbot follows this pattern:

User
  ↓
Chat Interface
  ↓
Backend Server
  ↓
AI API
  ↓
AI Model
  ↓
Generated Response
  ↓
Backend
  ↓
Chat Interface
  ↓
User

How Is an AI Chatbot Different From a Rule-Based Chatbot?

Rule-Based Chatbot AI Chatbot
Uses predefined rules. Uses an AI model to generate or interpret responses.
Usually handles fixed patterns. Can process more varied natural-language input.
Responses are generally predetermined. Responses may be generated dynamically.

What Do You Need to Build an AI Chatbot?

For a basic web chatbot, you can use:

  • HTML for the interface
  • CSS for styling
  • JavaScript for user interaction
  • Node.js for the backend
  • Express.js for HTTP routes
  • An AI API for the AI response

You can also use React, Vue, Angular, PHP, Python, Java, C#, or other backend technologies.

Project Architecture

We will create a simple application with this structure:

ai-chatbot/
│
├── server.js
├── package.json
├── .env
│
└── public/
    ├── index.html
    ├── style.css
    └── script.js

Step 1: Install Node.js

Download and install a current supported version of Node.js from the official Node.js website.

After installation, verify it from your terminal:

node --version
npm --version

You should see version numbers for both commands.

Step 2: Create the Project

Create a directory for your project:

mkdir ai-chatbot
cd ai-chatbot

Initialize a Node.js project:

npm init -y

Step 3: Install Express

Install Express:

npm install express

You will use Express to create a backend endpoint that receives messages from your frontend.

Step 4: Create the Frontend

Create public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chatbot</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div class="chat-container">
        <h1>AI Chatbot</h1>

        <div id="chatBox" class="chat-box"></div>

        <form id="chatForm">
            <input
                id="messageInput"
                type="text"
                placeholder="Ask something..."
                autocomplete="off"
                required
            >

            <button type="submit">Send</button>
        </form>
    </div>

    <script src="script.js"></script>

</body>
</html>

Step 5: Add CSS

Create public/style.css:

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    font-family: Arial, sans-serif;
    background: #f2f2f2;
}

.chat-container {
    width: min(700px, 92%);
    margin: 40px auto;
    background: white;
    padding: 20px;
    border-radius: 12px;
}

.chat-box {
    height: 450px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 15px;
}

.message {
    padding: 10px 12px;
    margin: 10px 0;
    border-radius: 8px;
}

.user {
    background: #eeeeee;
    text-align: right;
}

.bot {
    background: #f7f7f7;
}

#chatForm {
    display: flex;
    gap: 10px;
}

#messageInput {
    flex: 1;
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 8px;
}

button {
    padding: 12px 18px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

Step 6: Connect the Frontend to Your Backend

Create public/script.js:

const chatForm = document.getElementById("chatForm");
const messageInput = document.getElementById("messageInput");
const chatBox = document.getElementById("chatBox");

function addMessage(text, sender) {
    const message = document.createElement("div");

    message.className = `message ${sender}`;
    message.textContent = text;

    chatBox.appendChild(message);
    chatBox.scrollTop = chatBox.scrollHeight;
}

chatForm.addEventListener("submit", async (event) => {
    event.preventDefault();

    const message = messageInput.value.trim();

    if (!message) {
        return;
    }

    addMessage(message, "user");
    messageInput.value = "";

    try {
        const response = await fetch("/api/chat", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                message
            })
        });

        if (!response.ok) {
            throw new Error(`Request failed: ${response.status}`);
        }

        const data = await response.json();

        addMessage(data.reply, "bot");

    } catch (error) {
        console.error(error);
        addMessage(
            "Sorry, something went wrong. Please try again.",
            "bot"
        );
    }
});

The browser's Fetch API can send a JSON request using POST, and developers should check the response status before assuming the request succeeded.

Step 7: Create the Backend

Create server.js:

const express = require("express");

const app = express();
const PORT = 3000;

app.use(express.json());
app.use(express.static("public"));

app.post("/api/chat", async (req, res) => {
    try {
        const message = req.body.message;

        if (!message || typeof message !== "string") {
            return res.status(400).json({
                error: "Message is required."
            });
        }

        // Replace this section with your AI provider API call.
        const reply = `You asked: ${message}`;

        res.json({
            reply
        });

    } catch (error) {
        console.error(error);

        res.status(500).json({
            error: "Internal server error."
        });
    }
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

At this stage, the chatbot does not yet use an AI model. It simply returns the received message.

Now we need to replace the placeholder response with an actual AI API request.

Step 8: Add an AI API

Your backend can call an AI provider after receiving the user's message.

The general flow is:

POST /api/chat
       ↓
Validate message
       ↓
Create AI request
       ↓
Send request to AI API
       ↓
Receive AI response
       ↓
Extract answer
       ↓
Return JSON

The exact JavaScript code depends on the AI provider you select because request formats, SDKs, authentication methods, and model identifiers vary.

Example Provider Adapter

A clean way to design your application is to keep the provider-specific code inside a separate function.

async function callAIModel(message) {

    // Add the provider-specific API request here.

    const response = await fetch(
        "https://example-ai-provider.com/v1/chat",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${process.env.AI_API_KEY}`
            },
            body: JSON.stringify({
                message: message
            })
        }
    );

    if (!response.ok) {
        throw new Error(`AI API error: ${response.status}`);
    }

    const data = await response.json();

    return data.reply;
}

This example deliberately uses a placeholder API URL and response structure. Replace them with the current official API format of your chosen provider.

Step 9: Use Environment Variables

Create a file named .env:

AI_API_KEY=your_secret_api_key

Install the dotenv package:

npm install dotenv

Load environment variables in your application:

require("dotenv").config();

Then access the key with:

process.env.AI_API_KEY

Why Should You Never Put the API Key in Frontend JavaScript?

Your frontend code is delivered to users' browsers.

That means a secret embedded directly in frontend JavaScript can potentially be discovered by inspecting the application's code or network activity.

Instead use:

Browser
   ↓
Your Backend
   ↓
AI Provider

OpenAI's API documentation similarly recommends keeping API keys secret and away from client-side code. ([platform.openai.com](https://platform.openai.com/docs/api-reference/introduction?utm_source=chatgpt.com))

Step 10: Update the Backend

Your final route can call the provider adapter:

app.post("/api/chat", async (req, res) => {

    try {

        const message = req.body.message;

        if (!message || typeof message !== "string") {
            return res.status(400).json({
                error: "Valid message is required."
            });
        }

        const reply = await callAIModel(message);

        res.json({
            reply
        });

    } catch (error) {

        console.error("Chatbot error:", error);

        res.status(500).json({
            error: "Unable to generate a response."
        });
    }
});

Step 11: Run the Chatbot

Start your server:

node server.js

Then open:

http://localhost:3000

You should now see your chatbot interface.

Understanding the Complete Request

Suppose the user asks:

What is machine learning?

The browser sends:

POST /api/chat

{
    "message": "What is machine learning?"
}

Your server validates the input and sends the information to your selected AI provider.

The AI service returns a generated result.

Your server then returns something like:

{
    "reply": "Machine learning is a branch of artificial intelligence..."
}

The frontend displays that response inside the chat window.

Adding Conversation Memory

A basic chatbot only sends the latest message.

For a more useful chatbot, you can maintain conversation history.

For example:

[
    {
        "role": "user",
        "content": "What is Python?"
    },
    {
        "role": "assistant",
        "content": "Python is a programming language..."
    },
    {
        "role": "user",
        "content": "What is it used for?"
    }
]

Your application can send relevant conversation context with the new request, subject to the provider's API format and context limitations.

Where Should Conversation History Be Stored?

For a small prototype, conversation history can temporarily stay in memory.

For a real application, you may use a database such as:

  • PostgreSQL
  • MySQL
  • MongoDB
  • Redis for selected temporary or high-speed workloads

A simple database design might contain:

users
-----
id
name
email

conversations
-------------
id
user_id
created_at

messages
--------
id
conversation_id
role
content
created_at

Adding a System Instruction

You can also define how your chatbot should behave.

For example:

You are an educational assistant.
Explain technical concepts clearly.
Use simple examples.
Do not invent facts when you are uncertain.

The exact mechanism for passing such instructions depends on the AI API you are using.

Adding a Loading Indicator

AI requests can take time, so your interface should tell the user that a response is being generated.

For example:

addMessage("Thinking...", "bot");

In a more polished application, you can show a temporary loading animation and remove it after the API response arrives.

Handling API Errors

Your chatbot should handle errors gracefully.

Possible problems include:

  • Network failure
  • Invalid API credentials
  • Rate limiting
  • Invalid request data
  • Provider service errors
  • Timeouts
  • Application bugs

The frontend should show a helpful message instead of exposing internal server errors to users.

The backend should log useful diagnostic information while avoiding secrets and unnecessary sensitive data.

Input Validation

Never assume that user input is valid.

You can check:

  • Whether the message exists
  • Whether it is a string
  • Whether it exceeds the allowed length
  • Whether the user is authenticated, when required
  • Whether the request exceeds application limits

For example:

if (
    typeof message !== "string" ||
    message.trim().length === 0 ||
    message.length > 4000
) {
    return res.status(400).json({
        error: "Invalid message."
    });
}

Rate Limiting

A public chatbot can receive a large number of requests.

Without appropriate controls, automated users can increase your AI API consumption or overload your backend.

Production applications should consider:

  • Per-user rate limits
  • IP-based controls where appropriate
  • Authentication
  • Request quotas
  • Usage monitoring
  • Abuse detection

Content Safety

AI applications should be designed with the intended audience and use case in mind.

Depending on your application, you may need:

  • Input filtering
  • Output moderation
  • User reporting
  • Abuse controls
  • Age-appropriate experiences
  • Domain-specific safety rules

Do Not Trust Every AI Response

An AI-generated answer can be incorrect, incomplete, outdated, or misleading.

For applications involving important decisions, the chatbot should not be treated as an unquestionable authority.

For example, an educational chatbot can help explain a topic, but users should still verify important information using reliable sources.

Streaming Responses

Some AI APIs support streaming, allowing generated output to arrive incrementally instead of waiting for the complete response.

This can make a chatbot feel more responsive.

The conceptual flow becomes:

User sends question
       ↓
Backend starts AI request
       ↓
Partial output arrives
       ↓
Frontend displays text
       ↓
More output arrives
       ↓
Final response

The exact implementation depends on the provider and protocol you use.

Building a Chatbot With React

Once the basic version works, you can replace the plain HTML interface with React.

A React architecture could look like:

App
│
├── ChatWindow
│
├── MessageList
│
├── MessageBubble
│
├── ChatInput
│
└── LoadingIndicator

Your React frontend can continue calling the same backend endpoint:

POST /api/chat

Building a Chatbot With Python

You can also use Python for the backend.

A common stack could be:

  • Python
  • FastAPI or Flask
  • AI API
  • PostgreSQL or MongoDB

The same architecture remains:

Frontend
   ↓
Python Backend
   ↓
AI API
   ↓
AI Model

Adding a Database

A database becomes useful when you want users to log in and continue previous conversations.

You can store:

  • User accounts
  • Conversation IDs
  • Messages
  • Timestamps
  • Usage information
  • Application preferences

Adding Authentication

A production chatbot may require user authentication.

Authentication allows your application to associate conversations and usage with specific accounts.

Depending on your architecture, you can use sessions, secure cookies, OAuth, or token-based authentication.

Authentication and authorization are separate concepts: authentication identifies the user, while authorization determines what that user is allowed to access.

Chatbot Project Ideas

1. AI Study Assistant

Build a chatbot that explains programming, mathematics and computer-science concepts.

2. College FAQ Bot

Create a chatbot that answers questions about departments, courses, schedules and campus resources.

3. Website Support Bot

Build an assistant for answering common customer questions.

4. Coding Assistant

Create a chatbot that explains programming errors and concepts.

5. Document Chatbot

Allow users to search and ask questions about selected documents.

6. Resume Assistant

Build a chatbot that helps users improve resume content.

7. Product Assistant

Create a chatbot that helps visitors understand products and services.

8. Internal Knowledge Assistant

Create an employee-facing assistant that searches authorized internal information.

How to Make an AI Chatbot More Useful

A chatbot becomes much more useful when it is connected to relevant data and application functionality.

Possible improvements include:

  • Conversation memory
  • Document search
  • Retrieval-augmented generation
  • Database access
  • Tool calling
  • Authentication
  • User preferences
  • Analytics
  • Streaming
  • Voice input

What Is RAG in a Chatbot?

RAG stands for Retrieval-Augmented Generation.

Instead of relying only on information contained in a model's learned parameters, a RAG system retrieves relevant information from a data source and supplies that information to the model as context.

A simple RAG architecture is:

User Question
      ↓
Search / Retrieval
      ↓
Relevant Documents
      ↓
AI Model
      ↓
Answer

This is useful for document assistants, knowledge bases, support systems and other applications that need domain-specific information.

How to Deploy an AI Chatbot

Once the application works locally, you can deploy its frontend and backend using an appropriate hosting platform.

Common deployment options include:

  • Cloud virtual machines
  • Container platforms
  • Application hosting platforms
  • Serverless platforms
  • Managed backend services

Your deployment should protect environment variables, use HTTPS, monitor errors, and restrict access to administrative functionality.

Production Checklist

  • Secure API keys
  • Validate requests
  • Use authentication when needed
  • Add authorization checks
  • Add rate limiting
  • Handle API failures
  • Monitor API usage
  • Log important events
  • Protect user data
  • Use HTTPS
  • Test the application
  • Review provider limits and pricing

Testing Your Chatbot

Before releasing the application, test different types of input.

Examples:

  • Short questions
  • Long questions
  • Empty messages
  • Unexpected input
  • Repeated requests
  • Network failures
  • API failures
  • Rate-limit scenarios
  • Concurrent users

Important Performance Considerations

As usage increases, AI API consumption can become one of the major components of your application's operating cost.

Consider:

  • Reducing unnecessary context
  • Choosing an appropriate model
  • Limiting message length
  • Caching suitable results
  • Monitoring token or request usage
  • Applying quotas
  • Using asynchronous processing for suitable workloads

Beginner Roadmap for Building AI Chatbots

  1. Learn HTML and CSS.
  2. Learn JavaScript fundamentals.
  3. Learn HTTP and JSON.
  4. Learn REST APIs.
  5. Learn Node.js.
  6. Build a basic backend.
  7. Connect an AI API.
  8. Add conversation history.
  9. Add authentication.
  10. Add a database.
  11. Add security and rate limiting.
  12. Deploy the chatbot.

Final Thoughts

Building an AI chatbot is an excellent project for learning both software development and artificial intelligence.

You do not have to build an AI model from scratch. A practical architecture is to create a frontend for the conversation, use a backend to manage requests and secrets, and connect that backend to an AI API.

Start with a simple chatbot that sends one message and receives one response. Once that works, add conversation memory, authentication, databases, document retrieval, streaming, monitoring, and other features.

The most important lesson is to treat the chatbot as a software system, not just an API call. Good architecture, validation, security, error handling, privacy and testing are just as important as the AI model itself.


Frequently Asked Questions

Can a beginner build an AI chatbot?

Yes. A beginner who understands basic HTML, JavaScript, HTTP, JSON and backend development can start with a simple AI chatbot.

Do I need to train an AI model?

No. You can build many chatbot applications by connecting your software to an existing AI API.

Which programming language is best for an AI chatbot?

There is no single required language. JavaScript, TypeScript, Python, PHP, Java and other languages can be used depending on your architecture.

Can I build an AI chatbot with Node.js?

Yes. Node.js can handle the backend API route and communicate with an external AI service.

Can I build an AI chatbot with React?

Yes. React can be used to create the user interface while a backend handles the AI API communication.

Where should I store the AI API key?

Keep private API credentials on the server using environment variables or an appropriate secrets-management solution. Do not expose private credentials in browser JavaScript.

How does a chatbot remember previous messages?

The application can store conversation history and send relevant context with later requests. The exact implementation depends on the AI provider and your application's architecture.

What is RAG?

RAG stands for Retrieval-Augmented Generation. It combines retrieval of relevant information with AI generation so a chatbot can answer using selected external knowledge.

Can I make an AI chatbot for a college project?

Yes. AI study assistants, college FAQ bots, document assistants, coding helpers and other educational applications can make practical projects.

How much does an AI chatbot cost?

The cost depends on your AI provider, model, request volume, input and output size, infrastructure, and other services used by your application. Check current provider pricing before deployment.

Useful References

MDN Fetch API Guide
OpenAI API Documentation
Node.js Documentation
Express.js Documentation

Related Articles on CodeWithAV

What Is an AI API? Complete Beginner Guide
Best AI APIs for Developers in 2026
Chatbots vs AI Agents: What Is the Difference?
How AI Agents Work for Beginners
What Is Generative AI?

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.
Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.