logo Online Learner
  • Home
  • Learning Paths
  • Development
    Frontend Development Backend Development
  • Study Notes
  • Free Resume Builder
  • About Us
  • Contact Us
  • Login
  • Sign Up
  1. Learning Paths
  2. Next.js Tutorial
  3. Next js Authentication

Next.js Authentication

Next.js authentication is about proving who a user is, then remembering that fact across requests. In the App Router, you handle this on the server with cookies and Server Actions, so the browser never sees your secrets. Getting it right matters because a single mistake can expose private data or let anyone pretend to be someone else.

This tutorial builds a minimal login system step by step. You will create a Server Action that checks credentials, signs a session cookie with the jose library, and redirects the user. You will also write a getSession helper, protect a /dashboard page, and add a logout action. Along the way, you will learn why proxy.ts is only for optimistic redirects, not real security.

If you have not used Server Actions before, read Next.js Forms & Server Actions first. The session-cookie pattern here also connects to Next.js Middleware, which is now called proxy.ts in Next.js 16.

Security note: The code in this tutorial is for learning. It uses a hardcoded demo user and a simple session cookie. For production, use a vetted authentication library and a real database with hashed passwords. Never copy this code into a live application without adding proper security measures.

What Is Next.js Authentication and Why Does It Matter?

Next.js authentication is the process of verifying a user's identity, usually with an email and password, and storing that verified state in a session. Authentication answers "who are you?" while authorization answers "what are you allowed to do?" Both must happen on the server .

Here is the smallest mental model. A user submits a login form. The server checks the password. If it matches, the server creates a signed token and puts it in an HttpOnly cookie. On every later request, the server reads that cookie to know who the user is.

// Conceptual flow, not runnable code
// 1. User submits email and password
// 2. Server verifies credentials
// 3. Server creates a signed session token
// 4. Server sets it as an HttpOnly cookie
// 5. Later requests send the cookie automatically
// 6. Server reads and verifies the cookie

How it works: The cookie is the key. Because it is HttpOnly, JavaScript in the browser cannot read it. Because it is signed, the server can detect if someone tampered with it. This is the foundation of session-based authentication, and it works well with Next.js because Server Components and Server Actions can read and write cookies on the server .

Authentication vs Authorization in Plain Language

These two words sound similar but mean different things. Authentication is checking that the user is who they claim to be. Authorization is checking whether that user is allowed to do or see something.

Question Concept Example
Who is this user? Authentication Checking email and password at login
Can this user view the admin page? Authorization Checking if user.role === "admin"
Can this user delete this post? Authorization Checking if the post belongs to the user

How it works: A user can be authenticated but not authorized. For example, a logged-in customer is authenticated, but they are not authorized to open the admin dashboard. Always check both. Authentication tells you there is a valid session. Authorization tells you what that session can do .

How Session Cookies Work: HttpOnly, Secure, SameSite

A session cookie is a small piece of data stored by the browser and sent with every request to your server. Three flags make it safer: HttpOnly, Secure, and SameSite.

  • HttpOnly: JavaScript cannot read the cookie. This protects against cross-site scripting (XSS) attacks that try to steal the token.
  • Secure: The cookie is only sent over HTTPS. This prevents it from being intercepted on an insecure connection.
  • SameSite=lax: The cookie is not sent on most cross-site requests. This reduces the risk of cross-site request forgery (CSRF) attacks.
// app/actions/auth.ts (partial example)
import { cookies } from "next/headers";

export async function demo() {
  const cookieStore = await cookies();
  cookieStore.set("session", "token-value", {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}

How it works: In Next.js 16, cookies() is an async function. You must await it before calling .set() or .get() . The set method only works in a Server Action or Route Handler, because setting a cookie requires sending a response header, and Server Components cannot modify the response. The maxAge value is in seconds, so 60 * 60 * 24 * 7 is one week.

Building a Login Flow with a Server Action

A login flow takes credentials, verifies them, creates a session, and redirects the user. In the App Router, this fits naturally into a Server Action connected to a form.

Installing jose

# Terminal
npm install jose

Output: The jose package is added to your dependencies. It provides SignJWT and jwtVerify for creating and checking signed tokens.

The session helper

// lib/session.ts
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

const secretKey = new TextEncoder().encode(
  process.env.SESSION_SECRET ?? "dev-only-secret-change-me"
);

export type SessionPayload = {
  userId: string;
  email: string;
};

export async function createSession(payload: SessionPayload) {
  const token = await new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(secretKey);

  const cookieStore = await cookies();
  cookieStore.set("session", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}

export async function getSession(): Promise<SessionPayload | null> {
  const cookieStore = await cookies();
  const token = cookieStore.get("session")?.value;

  if (!token) return null;

  try {
    const { payload } = await jwtVerify(token, secretKey);
    return {
      userId: String(payload.userId),
      email: String(payload.email),
    };
  } catch {
    return null;
  }
}

export async function deleteSession() {
  const cookieStore = await cookies();
  cookieStore.delete("session");
}

export async function requireSession(): Promise<SessionPayload> {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }
  return session;
}

How it works: createSession signs a JWT with the user's ID and email, then stores it in an HttpOnly cookie. getSession reads the cookie, verifies the signature, and returns the payload or null. requireSession is a convenience wrapper that redirects to /login if there is no valid session. The SESSION_SECRET environment variable should be a long random string in production. The fallback value is only for local development .

The login Server Action and page

// app/actions/auth.ts
"use server";

import { createSession } from "@/lib/session";

// Demo user only. Never hardcode passwords in production.
const DEMO_USER = {
  id: "1",
  email: "student@example.com",
  password: "password123",
};

export type LoginState = {
  error: string | null;
};

export async function login(
  _prevState: LoginState,
  formData: FormData
): Promise<LoginState> {
  const email = formData.get("email");
  const password = formData.get("password");

  if (typeof email !== "string" || typeof password !== "string") {
    return { error: "Email and password are required" };
  }

  if (email !== DEMO_USER.email || password !== DEMO_USER.password) {
    return { error: "Invalid email or password" };
  }

  await createSession({ userId: DEMO_USER.id, email: DEMO_USER.email });
  return { error: null };
}
// app/login/page.tsx
"use client";

import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { login, type LoginState } from "../actions/auth";

const initialState: LoginState = { error: null };

export default function LoginPage() {
  const [state, formAction] = useActionState(login, initialState);
  const router = useRouter();

  useEffect(() => {
    if (state.error === null) {
      router.push("/dashboard");
    }
  }, [state, router]);

  return (
    <form action={formAction}>
      <input name="email" type="email" placeholder="Email" />
      <input name="password" type="password" placeholder="Password" />
      {state.error && <p>{state.error}</p>}
      <button type="submit">Log in</button>
    </form>
  );
}

Browser shows: Submitting the demo credentials redirects to /dashboard. Submitting wrong credentials shows Invalid email or password below the form.

How it works: The Server Action checks the credentials against the hardcoded demo user. If they match, it calls createSession, which sets the cookie. The Client Component uses useActionState to track the result and useRouter to navigate on success. In a real app, you would call redirect("/dashboard") inside the Server Action instead of using useEffect in the client. The client-side redirect is shown here to keep the form state visible during the demo .

Protecting Pages with a Data Access Layer

A data access layer is a server-only module that checks the session before returning protected data. You should call it from every page, layout, and Server Action that needs to know who the user is.

// app/dashboard/page.tsx
import { requireSession } from "@/lib/session";

export default async function DashboardPage() {
  const session = await requireSession();

  return (
    <main>
      <h1>Dashboard</h1>
      <p>Welcome, {session.email}</p>
    </main>
  );
}

Browser shows: If you have a valid session, you see the dashboard with your email. If you do not, you are redirected to /login.

How it works: requireSession calls getSession, which reads and verifies the cookie. If there is no valid session, it redirects. This check happens on the server, before any data is fetched or rendered. Even if someone finds the URL, they cannot see the page without a valid cookie. This is the most important layer of protection .

Proxy.ts for Optimistic Redirects Only

In Next.js 16, the file previously called middleware.ts is now proxy.ts, and the exported function is named proxy . You can use it to redirect users who have no session cookie before they even reach a page. But it must not be your only security check.

// proxy.ts (project root or src/)
import { NextResponse } from "next/server";
import { type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const session = request.cookies.get("session");

  if (!session && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"],
};

Output: A request to /dashboard without a session cookie is redirected to /login. A request with any session cookie is allowed through, even if the cookie is invalid.

How it works: proxy.ts runs before the route is rendered. It is a fast, coarse check that only looks at whether a cookie exists. It does not verify the signature or check if the user is allowed to see specific data. That is why it is called "optimistic." It improves the user experience by redirecting early, but the real authorization must happen in the data access layer. Relying on proxy.ts alone is dangerous because a misconfigured matcher can leave a route unprotected, and a forged cookie can pass a simple existence check .

Logout and Session Cleanup

Logging out means deleting the session cookie. A Server Action is the right place to do this because it can modify response headers.

// app/actions/auth.ts (add this function)
"use server";

import { deleteSession } from "@/lib/session";
import { redirect } from "next/navigation";

export async function logout() {
  await deleteSession();
  redirect("/login");
}
// app/dashboard/logout-button.tsx
"use client";

import { logout } from "../actions/auth";

export default function LogoutButton() {
  return (
    <form action={logout}>
      <button type="submit">Log out</button>
    </form>
  );
}

Browser shows: Clicking "Log out" deletes the cookie and sends you to /login. Visiting /dashboard afterwards redirects you back to /login.

How it works: deleteSession calls cookieStore.delete("session"), which tells the browser to remove the cookie. The redirect function then navigates the user. The logout action is connected to a form, which means it works even without JavaScript, following the same progressive enhancement pattern as login.

Ready-Made Auth Libraries: A Short Overview

Building authentication from scratch is a good learning exercise, but production apps should use a maintained library. These libraries handle password hashing, session management, OAuth providers, and security updates for you.

  • Auth.js (formerly NextAuth): A popular open-source library with many providers. As of late 2025, it is in security-patch mode, and its maintainers recommend Better Auth for new projects .
  • Clerk: A hosted service with prebuilt UI components and a generous free tier. Good if you want to move fast and do not mind vendor lock-in.
  • Better Auth: A newer open-source library that stores sessions in your database. It is actively developed and has become a common recommendation for new self-hosted projects .

Never store plain-text passwords. Use a vetted hashing library like bcrypt or argon2 to hash passwords before saving them to the database. Hashing is a one-way process: you can check a password against a hash, but you cannot turn the hash back into the password. Even if your database is leaked, attackers cannot read the original passwords .

Common Mistakes and Best Practices

Security disclaimer: The examples on this page are for education. They use a hardcoded user and a simple secret. A production system needs a real database, hashed passwords, HTTPS, a strong secret stored in environment variables, and a maintained auth library. Do not deploy demo authentication code.
  • Relying on proxy.ts as the only security check. A proxy check can be bypassed if the matcher misses a route or if a forged cookie passes a simple existence test. Always verify the session in the data access layer, close to where data is read or changed .
  • Forgetting to await cookies(). In Next.js 16, cookies() returns a Promise. Calling cookies().set(...) without await throws an error or silently fails, and your session cookie is never set .
  • Storing sensitive data in the cookie payload. A JWT is signed but not encrypted by default. Anyone can decode the payload and read it. Only put non-sensitive identifiers like a user ID in the token, never passwords or private data.
  • Using a weak or hardcoded secret. The SESSION_SECRET must be a long random string stored in environment variables. If an attacker knows the secret, they can forge valid tokens and impersonate any user.
  • Not setting HttpOnly, Secure, and SameSite. Without these flags, the cookie is vulnerable to XSS and CSRF attacks. Always set all three, and only use secure: false in local development without HTTPS .
  • Trying to set cookies in a Server Component. The .set() method only works in a Server Action or Route Handler. In a Server Component, you can read cookies but not write them .

Real-World Example: A Protected Dashboard

This example brings the pieces together: a session helper, a login action, and a protected page. It uses a hardcoded demo user for clarity.

// lib/session.ts (simplified for this example)
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

const secretKey = new TextEncoder().encode(
  process.env.SESSION_SECRET ?? "dev-only-secret"
);

export type SessionPayload = { userId: string; email: string };

export async function createSession(payload: SessionPayload) {
  const token = await new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setExpirationTime("7d")
    .sign(secretKey);

  const cookieStore = await cookies();
  cookieStore.set("session", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}

export async function getSession(): Promise<SessionPayload | null> {
  const token = (await cookies()).get("session")?.value;
  if (!token) return null;
  try {
    const { payload } = await jwtVerify(token, secretKey);
    return { userId: String(payload.userId), email: String(payload.email) };
  } catch {
    return null;
  }
}

export async function requireSession(): Promise<SessionPayload> {
  const session = await getSession();
  if (!session) redirect("/login");
  return session;
}

export async function deleteSession() {
  (await cookies()).delete("session");
}
// app/actions/auth.ts
"use server";

import { createSession, deleteSession } from "@/lib/session";
import { redirect } from "next/navigation";

const DEMO_USER = {
  id: "1",
  email: "student@example.com",
  password: "password123",
};

export type LoginState = { error: string | null };

export async function login(
  _prevState: LoginState,
  formData: FormData
): Promise<LoginState> {
  const email = formData.get("email");
  const password = formData.get("password");

  if (typeof email !== "string" || typeof password !== "string") {
    return { error: "Email and password are required" };
  }

  if (email !== DEMO_USER.email || password !== DEMO_USER.password) {
    return { error: "Invalid email or password" };
  }

  await createSession({ userId: DEMO_USER.id, email: DEMO_USER.email });
  redirect("/dashboard");
}

export async function logout() {
  await deleteSession();
  redirect("/login");
}
// app/dashboard/page.tsx
import { requireSession } from "@/lib/session";
import LogoutButton from "./logout-button";

export default async function DashboardPage() {
  const session = await requireSession();

  return (
    <main>
      <h1>Dashboard</h1>
      <p>Logged in as: {session.email}</p>
      <LogoutButton />
    </main>
  );
}

Line-by-line explanation:

  • lib/session.ts exports four helpers: createSession (signs and sets the cookie), getSession (reads and verifies the cookie), requireSession (redirects if no session), and deleteSession (removes the cookie).
  • app/actions/auth.ts contains the login and logout Server Actions. Login validates against the hardcoded demo user, creates the session, and redirects to /dashboard.
  • app/dashboard/page.tsx is a Server Component that calls requireSession before rendering. If there is no valid session, the user is redirected to /login.
  • The logout button is a small Client Component that submits a form to the logout action. The action deletes the cookie and redirects to /login.

Summary

  • Next.js authentication with session cookies means checking credentials in a Server Action, signing a token, and storing it in an HttpOnly cookie.
  • cookies() is async in Next.js 16. Always await it before reading or writing.
  • Authentication is who the user is. Authorization is what they can do. Check both on the server, close to your data.
  • Use a data access layer with a requireSession helper to protect pages and Server Actions. Use proxy.ts only for optimistic redirects.
  • Never store plain-text passwords. Use a vetted hashing library, and prefer a maintained auth library for production.
  • Set HttpOnly, Secure, and SameSite on every session cookie.

Now that you can identify users, the next step is storing their data. Continue with Next.js Database with Prisma.

Frequently Asked Questions

Why is cookies() async in Next.js 16?

Next.js 16 made cookies() asynchronous to support streaming and better performance. You must await it before calling .get() or .set(). If you forget, you may get a warning or an error saying the function was not awaited. Older versions of Next.js had a synchronous cookies() function, which is why some tutorials show it without await.

Can I set a cookie in a Server Component?

No. Server Components cannot modify response headers, and setting a cookie requires a Set-Cookie header. You can read cookies in a Server Component, but to set or delete them you must use a Server Action or a Route Handler. This is why login and logout logic belongs in Server Actions.

What is the difference between proxy.ts and middleware.ts?

In Next.js 16, middleware.ts was renamed to proxy.ts, and the exported function is now called proxy. The behavior is similar: it runs before a route is rendered and can redirect or rewrite requests. The rename clarifies that it is a network boundary, not a place for full authorization logic. Use it for optimistic checks only.

Do I need a database for Next.js authentication?

For production, yes. You need a database to store users, hashed passwords, and session records if you use database sessions. The tutorial uses a hardcoded demo user to focus on the mechanics. A real app would query the database in the login action, compare the password with a hash, and store sessions in the database or a signed cookie.

Why should I use an auth library instead of building my own?

Authentication has many edge cases: password hashing, session invalidation, OAuth flows, CSRF protection, and security updates. A maintained library handles these correctly and receives patches when vulnerabilities are found. Building your own is a good learning exercise, but for production, a library like Better Auth, Clerk, or Auth.js reduces risk and saves time.

Practice Exercises

Easy: Create a session helper

Write a getSession function that reads a cookie named "session" and returns its value, or null if the cookie is missing. Use cookies() from next/headers.

Show solution
// lib/session.ts
import { cookies } from "next/headers";

export async function getSession(): Promise<string | null> {
  const cookieStore = await cookies();
  return cookieStore.get("session")?.value ?? null;
}

cookies() is awaited, and the optional chaining operator returns null when the cookie is missing.

Easy: Add a logout action

Create a Server Action called logout that deletes the "session" cookie and redirects to /login.

Show solution
// app/actions/auth.ts
"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export async function logout() {
  const cookieStore = await cookies();
  cookieStore.delete("session");
  redirect("/login");
}

The .delete() method removes the cookie, and redirect sends the user to the login page.

Medium: Protect a page with requireSession

Create a requireSession function that calls getSession and redirects to /login if the session is null. Then use it in a /profile page.

Show solution
// lib/session.ts (add this function)
import { redirect } from "next/navigation";

export async function requireSession(): Promise<string> {
  const session = await getSession();
  if (!session) redirect("/login");
  return session;
}
// app/profile/page.tsx
import { requireSession } from "@/lib/session";

export default async function ProfilePage() {
  const session = await requireSession();
  return <p>Session: {session}</p>;
}

requireSession centralizes the redirect logic, so every protected page uses the same check.

Challenge: Add a role check for authorization

Extend the session payload to include a role field ("user" or "admin"). Write a requireAdmin function that redirects to /dashboard if the session exists but the role is not "admin".

Show solution
// lib/session.ts (updated types and new function)
import { redirect } from "next/navigation";

export type SessionPayload = {
  userId: string;
  email: string;
  role: "user" | "admin";
};

export async function requireAdmin(): Promise<SessionPayload> {
  const session = await getSession();
  if (!session) redirect("/login");
  if (session.role !== "admin") redirect("/dashboard");
  return session;
}

This separates authentication (is there a session?) from authorization (is the role admin?). Both checks happen on the server before any data is rendered.



Shaikh Abdul Shahid
Written by Shaikh Abdul Shahid

A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.

GitLab LinkedIn
X
0 likes
Your Feedback

Help us improve by sharing your thoughts.

IT and Digital Marketing
keyboard_arrow_left Previous
Next keyboard_arrow_right
Online Learner Logo

Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.

Quick Links

  • Frontend Development
  • Backend Development
  • Learning Paths
  • Notes
  • Free Resume Builder
  • Portfolio

Company

  • About Us
  • Contact Us
  • Terms & Conditions
  • Disclaimer

© 2023 - 2026 OnlineLearner.in | All Rights Reserved.

logo
  • code Frontend
  • storage Backend
  • live_help Interviews
  • work_outline PHP Frameworks
  • settings Routine Use
  • book Blogs
Frontend
  • HTML Tutorial
    • HTML Introduction
    • HTML Tags
    • HTML Elements
    • HTML Attributes
    • HTML Heading
    • HTML Paragraph
    • HTML Formatting
    • HTML Quotations
    • HTML Comments
    • HTML Styles
    • HTML Color
    • HTML CSS
    • HTML Images
    • HTML Favicon
    • HTML Links
    • HTML DIV
    • HTML Tables
    • HTML Table Size
    • HTML Table Head
    • Table Padding & Spa...
    • Table colspan rowspsn
    • HTML Table Styling
    • HTML Colgroup
    • HTML List
    • HTML Block & Inline
    • HTML Classes
    • HTML Id
    • HTML Iframes
    • HTML Head
    • HTML Layout
    • HTML Semantic Elements
    • HTML Style Guide
    • HTML Forms
    • HTML Form Attribute
    • HTML Form Element
    • HTML input type
    • HTML Computer code
    • HTML Entity
    • HTML Symbol
    • HTML Emojis
    • HTML Charset
    • HTML Input Form Att...
    • HTML URL Encoding
  • CSS Tutorial
    • CSS Introduction
    • CSS Syntax
    • CSS Selector
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Background color
    • CSS background-image
    • CSS Borders
    • CSS Margins
    • CSS Height, Width a...
    • CSS Box Model
    • CSS Outline
    • CSS Text
    • CSS Fonts
    • CSS Icon
    • CSS Links
    • CSS Tables
    • CSS Display
    • CSS Maximum Width
    • CSS Position
    • z-index Property
  • JavaScript Tutorial
    • What is JavaScript
    • JS Syntax
    • JS Variables
    • JS Data Types
    • JS Operators
    • JS Control Flow - IF
    • JS Control Flow - S...
    • JS Control Flow - Loop
    • JS Function
    • JS Object Methods
    • JS Anonymous Funct...
    • JS Recursive Function
    • JS Default Parameters
    • JS this Keyword
    • What is an Array in...
    • What are JavaScript...
    • Error Handling in J...
    • DOM Selection in Ja...
    • DOM Traversal in Ja...
    • Manipulating Elemen...
    • Event Handling in J...
    • JavaScript Event Li...
    • JavaScript Event Pr...
    • Form Handling in Ja...
    • Dynamic Styling in ...
    • JavaScript DOM Elem...
    • Window Object in Ja...
    • What is Local Storage?
    • Regular Expressions...
  • Jquery Tutorial
    • What is jQuery?
    • Benefits of using j...
    • Include jQuery
    • Selectors.
    • Methods.
    • The $ symbol and sh...
    • Selecting elements
    • Getting and setting...
    • Adding and removing...
    • Modifying CSS and c...
    • Binding and Unbindi...
    • Common events: clic...
    • Event delegation
    • Using .on() for dyn...
    • Showing and hiding ...
    • Fading elements in ...
    • Sliding elements up...
    • .animate()
    • Understanding AJAX
    • .ajax()
    • .load(), .get(), .p...
    • Handling responses ...
    • Parent
    • Chlid
    • Siblings
    • Filtering Elements
    • Using find
    • Selecting form elem...
    • Getting form values
    • Setting form values
    • Form validation
    • Handling form submi...
    • jQuery plugins
    • Sliders plugins
    • $.each()
    • $.trim()
    • $.extend()
    • Data attributes
    • Debugging jQuery code
  • Bootstrap 4
    • What is Bootstrap
    • Benefits of using
    • Setting up
    • Container
    • Row and Column
    • Grid Classes
    • Breakpoints
    • Offsetting Columns
    • Column Ordering
    • Basic Typography
    • Text Alignment
    • Text colors
    • Backgrounds
    • Display
    • Font Size Utilities
    • Buttons
    • Navs and Navbar
    • Forms
    • Cards
    • Alerts
    • Badges
    • Progress Bars
    • Margin
    • Padding
    • Sizing
    • Flexbox
    • Dropdowns
    • Modals
    • Tooltips
    • Popovers
    • Collapse
    • Carousel
    • Images
    • Tables
    • Jumbotron
    • Media Object
  • Git
    • Understanding Versi...
    • Download and Instal...
    • Git Configure
    • Git Initialize
    • Add Changes to Staging
    • Commit Changes
    • Branching
    • Merging
    • Remote Repository
    • Understanding Git C...
    • Stashing Changes
    • Viewing Commit History
    • Undoing Changes
  • Ajax Tutorial
    • Ajax Fundamentals
    • Ajax Working
    • XMLHttpRequest Fetch
    • Synchronous vs Asyn...
    • Ajax Advantages
    • Ajax Disadvantages
    • $.ajax() method
    • Ajax GET request
    • Ajax POST Request
    • Json Response
    • Ajax Errors
    • Ajax Form
  • React Tutorial
    • What is React? Begi...
    • React Environment S...
    • React Fundamentals:...
    • Functional vs Class...
    • Props in React Expl...
    • State and setState ...
    • React Event Handling
    • React Conditional R...
    • React Lists and Keys
    • Styling in React In...
    • Styling in React Us...
    • Styling in React Us...
    • Tailwind CSS with R...
    • Tailwind vs CSS Mod...
    • React Hooks
    • React useState Hook
    • React useEffect Hook
    • React useRef Hook
    • React useContext Hook
    • React useReducer Hook
    • Custom Hooks in React
    • React Router – In...
    • Installing React Ro...
    • React Router – Ro...
    • React Router – Ne...
    • React Router URL Pa...
    • React Router Protec...
    • React Router Redire...
    • State Management in...
    • Redux State Managem...
    • Redux Toolkit Expla...
    • Redux Toolkit vs Re...
    • Controlled vs Uncon...
    • Handling Form Input...
    • API Integration in ...
    • Axios in React – ...
    • Handling Loading an...
    • Async Await in Java...
    • Displaying API Data...
    • CRUD Operations in ...
    • React Performance O...
    • React Performance O...
  • Tailwind
    • Introduction to Tai...
    • Utility-First CSS E...
    • Tailwind CSS vs Boo...
    • When and Why to Use...
    • Real-World Use Case...
    • Tailwind CSS Instal...
    • Installing Tailwind...
    • Tailwind CSS with V...
    • Setting Up Tailwind...
    • Install Tailwind CS...
    • Tailwind CSS Colors...
    • Tailwind CSS Backgr...
    • Tailwind CSS Paddin...
    • Tailwind CSS Margin...
    • Tailwind CSS Width ...
    • Tailwind CSS Height...
    • Tailwind CSS Border...
    • Tailwind CSS Border...
    • Tailwind CSS Text S...
    • Tailwind CSS Box Sh...
    • Tailwind CSS Opacit...
    • Tailwind CSS Cursor...
    • Tailwind CSS Overfl...
    • Tailwind CSS Font S...
    • Tailwind CSS Font W...
    • Tailwind CSS Text A...
    • Tailwind CSS Line H...
    • Tailwind CSS Letter...
    • Tailwind CSS Text T...
    • How to Use Google F...
    • Flexbox with Tailwi...
    • Justify Content in ...
    • Align Items in Tail...
    • Flex Direction in T...
    • Gap in Tailwind CSS...
    • Flexbox with Tailwi...
    • Grid System in Tail...
    • Grid System in Tail...
    • Responsive Design i...
    • Positioning & Z-Ind...
    • Background Colors i...
    • Background Images i...
    • Gradients in Tailwi...
    • Image Object-Fit in...
    • Image Overlay Effec...
    • Buttons in Tailwind...
    • Hover & Focus State...
    • Buttons and Forms i...
    • Cards and Sections ...
    • Navbar and Footer D...
  • TypeScript Tutorial
    • TypeScript Introduc...
    • TypeScript Installa...
    • First TypeScript Pr...
    • TypeScript Basic Types
    • Type Inference and ...
    • TypeScript Arrays a...
    • TypeScript Enums
    • TypeScript Any, Unk...
    • TypeScript Interfaces
    • Type Aliases and Un...
    • Intersection Types
    • Literal Types
    • Functions in TypeSc...
    • Classes in TypeScript
    • Access Modifiers an...
    • Abstract Classes
    • TypeScript Generics
    • TypeScript Utility ...
    • Type Guards and Nar...
    • Modules and Namespaces
    • TypeScript Decorators
    • TypeScript with React
    • TypeScript with Nod...
  • Next.js Tutorial
    • Introduction to Nex...
    • Next js Setup and P...
    • Next js App Router ...
    • Next js Pages and L...
    • Next js Navigation ...
    • Next js Dynamic Routes
    • Next js Route Groups
    • Next js Middleware
    • Server vs Client Co...
    • SSR, SSG and ISR Ex...
    • Next js Loading and...
    • Next js Data Fetching
    • Next js Route Handl...
    • Next js Forms and S...
    • Next js Caching and...
    • Next js Image Optim...
    • Next js Metadata an...
    • Tailwind CSS with N...
    • Next js Authentication
    • Next js Database wi...
    • Deploy Next js to V...
    • Next js Mini Projec...
Backend
  • PHP Tutorial
    • PHP Introduction
    • PHP Installation
    • PHP Syntax
    • PHP Comments
    • PHP Variable
    • PHP Echo
    • PHP Data Types
    • PHP Strings
    • PHP Constant
    • PHP Maths
    • PHP Number
    • PHP Operators
    • PHP if else & if el...
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Array
    • PHP OOps
    • PHP Class & Object
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modfiers
    • PHP Inheritance
    • PHP Final Keyword
    • PHP Class Constant
    • PHP Abstract Class
    • PHP Superglobals
    • PHP Regular Expression
    • PHP Interfaces
    • PHP Static Method
    • PHP Static Properties
    • PHP Namespace
    • PHP Iterable
    • PHP Form Introduction
    • PHP Form Validation
    • PHP Complete Form
    • PHP Date and Time
    • PHP Include Files
    • PHP - Files & I/O
    • File Upload
    • PHP Cookies
    • PHP SESSION
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP AND Exceptions
    • PHP Connect database
  • PHP Functions
    • strlen
    • strtoupper
    • strtolower
    • ucfirst
    • ucwords
    • substr
    • str_replace
    • strpos
    • trim in php
    • explode
    • implode
    • count in php
    • array_merge
    • array_push
    • array_pop
    • array_shift
    • array_unshift
    • in_array
    • array_keys
    • array_values
    • array_filter
    • array_map
    • sort
    • asort
    • ksort
    • abs
    • round
    • ceil
    • floor
    • rand
    • mt_rand
    • max
    • min
    • pow
    • sqrt
    • date
    • time
    • strtotime
    • mktime
    • date_diff
    • getdate
    • fopen
    • fread
    • fwrite
    • fclose
    • file_get_contents
    • file_put_contents
    • file_exists
    • unlink
    • filesize
    • is_readable
    • is_writable
    • urlencode
    • urldecode
    • parse_url
    • http_build_query
    • isset
    • empty
    • is_numeric
    • is_array
    • is_string
    • filter_var
    • htmlspecialchars
    • md5
    • sha1
    • password_hash
    • password_verify
    • die
    • exit
    • var_dump
    • print_r
    • include
    • require
    • json_encode
    • json_decode
    • sleep
  • PHP and MySQL Functions
    • mysqli_connect
    • mysqli_select_db
    • mysqli_query
    • mysqli_prepare
    • mysqli_stmt_execute
    • mysqli_multi_query
    • mysqli_fetch_assoc
    • mysqli_fetch_array
    • mysqli_fetch_row
    • mysqli_fetch_object
    • mysqli_num_rows
    • mysqli_real_escape_...
    • mysqli_insert_id
    • mysqli_affected_rows
    • mysqli_error
    • mysqli_close
    • mysqli_commit
    • mysqli_rollback
  • Python Tutorial
    • What is Python?
    • Install Python on W...
    • Install Python on L...
    • Install Python on m...
    • IDE Setup
    • Python syntax
    • Python Comments
    • Python Indentation
    • Python Variables
    • Python Data Types
    • Python Numeric
    • Python Boolean
    • Python String
    • Python List
    • Python Tuple
    • Python Range
    • Python Dictionary
    • Python Arithmetic O...
    • Python Assignment O...
    • Python Comparison O...
    • Python Logical Oper...
    • Python Bitwise Oper...
    • Python if condition
    • Python if else cond...
    • Python For Loop
    • Python While Loop
    • Python break, conti...
  • MYSQL
    • SQL Introduction
    • Syntax
    • Select statement
    • Select Distinct
    • WHERE Clause
    • Order By
    • SQL AND Operator
    • SQL OR Operator
    • SQL NOT Operator
    • SQL LIKE
    • SQL IN
    • SQL BETWEEN
    • SQL INSERT INTO
    • SQL NULL Values
    • SQL UPDATE
    • SQL DELETE
    • SQL TOP, LIMIT, FET...
    • SQL MIN() and MAX()...
    • SQL COUNT() Function
    • SQL SUM()
    • SQL AVG()
    • SQL Aliases
    • SQL JOIN
    • SQL INNER JOIN
    • SQL LEFT JOIN
    • SQL RIGHT JOIN
    • SQL FULL OUTER JOIN
    • SQL Self Join
    • SQL UNION
    • SQL GROUP BY
    • SQL HAVING
    • SQL EXISTS
    • SQL ANY and ALL
    • SQL SELECT INTO
    • SQL INSERT INTO SELECT
    • SQL CASE
    • SQL NULL Functions
    • SQL Stored Procedures
    • SQL Comments
    • SQL Operators
    • SQL CREATE DATABASE
    • SQL DROP DATABASE
    • SQL BACKUP DATABASE
    • SQL CREATE TABLE
    • SQL DROP TABLE
    • SQL ALTER TABLE
    • SQL Constraints
    • SQL NOT NULL
    • SQL UNIQUE Constraint
    • SQL PRIMARY KEY
    • SQL FOREIGN KEY
    • SQL CHECK Constraint
    • SQL CREATE INDEX
    • SQL AUTO INCREMENT
    • SQL Dates
    • SQL Views
    • SQL Injection
    • SQL Hosting
    • SQL Data Types
  • Node Js
    • What is Node.js?
    • Why use Node.js?
    • Installing Node.js
    • First Node.js progr...
    • Event Loop
    • Understanding npm
    • What are Modules?
    • fs (File System)
    • Http Module
    • Path Module
    • Creating custom mod...
    • Exporting and impor...
    • Setting up a basic ...
    • Handling requests a...
    • Serving HTML
    • Serving CSS
    • Serving JavaScript
  • Python MySQL
    • Database Connection
    • Table Creation
    • Insert Query
    • Select Query
    • Update Query
    • Delete Query
    • Where Clause Query
    • Limit Clause Query
    • Join Tables
    • Order By Query
    • Group By Query
    • Aggregate Functions
    • Parameterized Query
  • Java Tutorials
    • Java Introduction
    • Java Installation
    • Java Syntax
    • Java Comments
    • Java Variables
    • Java DataTypes
    • Java Operators
    • Java Conditionals
    • Java Looping
    • Java Arrays
    • Java Methods
    • Java Classes
    • Java Objects
    • Java Constructors
    • Java Inheritance
    • Java Polymorphism
    • Java Encapsulation
    • Java Abstraction
    • Java Exception
    • Java Interfaces
    • Java File Handling
    • Java Threads
    • Java Access Modifiers
    • Java Static Keyword
    • Java Final Keyword
    • Java Nested Class
    • Java Synchronization
  • Docker
    • Introduction to Docker
    • Installing Docker
    • Docker Architecture
    • Docker Images
    • Docker Containers
    • Dockerfile Basics
    • Docker Volumes
    • Docker Networking
    • Docker Compose
    • Docker Hub & Registry
    • Multi-Stage Builds
    • Docker with Nginx
    • Docker with MySQL
    • Docker with PHP & L...
    • Docker Environment ...
    • Docker Logs & Debug...
    • Docker Security Bes...
    • Docker Swarm Basics
    • Docker vs Virtual M...
    • Real World Docker P...
Interviews
  • PHP Interviews
    • What is PHP?
    • What does PHP stand...
    • PHP Advantages
    • Difference between ...
    • Start a PHP script?
    • Commenting in PHP
    • Variable in PHP
    • Different types of ...
    • Different types of ...
    • Array in PHP
    • Difference between ...
    • Retrieve data from ...
    • PHP handle errors
    • Sessions in PHP
    • PHP Cookie
    • What are the main f...
    • What are the differ...
    • What are the differ...
  • Java Interview Questions
    • Java Basics – Wha...
    • What is the differe...
    • What are the OOP co...
    • Why is the main met...
    • What are the differ...
    • What is the differe...
    • What is Method Over...
    • What is the Differe...
    • What is the Constru...
    • What are the Access...
    • What is the this Ke...
    • What is the super K...
    • What is the static ...
    • What is the final K...
    • What is Exception H...
    • What are Checked an...
    • What is the Differe...
    • What are Multithrea...
    • What is the Java Co...
    • What is the Differe...
    • What is the Differe...
    • What is the Differe...
    • What is the Differe...
    • How Does HashMap Wo...
    • What is the Differe...
    • What is the Differe...
    • What is the String ...
    • What is the Differe...
    • What is Garbage Col...
    • What is the Differe...
    • What is a Lambda Ex...
    • What is the Stream ...
    • What are Optional C...
    • What is the Differe...
    • What are the Key Fe...
    • What is the Record ...
  • React Interviews
    • What is React.js
    • Help In Interviews
    • Features of React
    • What is JSX
    • React's Virtual DOM
    • State and Props
    • React handle data b...
    • React Component
    • setState() method.
    • Controlled Components
    • Lifecycle Methods
    • Significance of keys
    • What are the differ...
  • Laravel Interviews
    • What is Laravel?
    • What are the key fe...
    • Explain the concept...
    • What is a controlle...
    • What is Blade templ...
    • How does Eloquent O...
    • Explain the concept...
    • What are middleware...
    • How do you create a...
    • What is CSRF protec...
    • What is the purpose...
    • What is the purpose...
    • Explain the concept...
    • How do you create a...
    • What is the purpose...
    • How do you define r...
    • What are named rout...
    • Explain the use of ...
    • What is the purpose...
    • What are service pr...
  • SQL Interviews
    • What is SQL?
    • What are the differ...
    • What is the differe...
    • What is a primary key?
    • What is a foreign key?
    • What are the differ...
    • What is the differe...
    • What is the use of ...
    • What is the differe...
    • What is an index in...
    • What types of index...
    • What is a subquery?
    • How do you use the ...
    • How can you find th...
    • Explain the use of ...
    • What is a view?
    • What are the limita...
    • Write a query to fe...
    • Write a query to fe...
    • Write a query to co...
    • Write a query to fe...
    • Write a query to fe...
    • Write a query to fi...
    • Write a query to fe...
    • Write a query to re...
    • Write a query to ge...
    • Write a query to ge...
    • Write a query to li...
    • Write a query to fi...
    • Write a query to fi...
    • Write a query to ge...
    • Write a query to fi...
    • Write a query to co...
    • Write a query to fi...
    • Write a query to li...
    • Write a query to fe...
    • Write a query to fi...
    • Write a query to fe...
    • Write a query to ge...
    • Write a query to co...
    • Write a query to fe...
  • JavaScript Interview Questions
    • What Exactly is Jav...
    • What are the data t...
    • What is the differe...
    • JavaScript double e...
    • What is a Closure i...
    • What is Hoisting in...
    • Understanding "this...
    • What Are JavaScript...
    • Null vs Undefined i...
    • How Does JavaScript...
    • What is a Promise i...
    • Async/Await in Java...
    • Event Delegation in...
    • JavaScript Modules ...
    • How to Prevent a Fu...
    • JavaScript Intervie...
    • JavaScript Intervie...
    • What is bind() in J...
    • Event Bubbling vs. ...
    • Deep Copy vs Shallo...
    • What is the new Key...
PHP Frameworks
  • Laravel
    • Laravel Topics
    • Laravel 7 Installation
    • Install laravel 8
    • Laravel 8 Routing
    • Laravel Controllers
    • Views and Blade lar...
    • Database and Eloque...
    • Authentication and ...
    • CSRF Protection
    • Laravel Model
    • Database: Query Bui...
Routine Use
  • Linux
    • How to Delete a Fil...
    • Install lemp in ubu...
    • How to check packag...
    • Navigating the File...
    • Managing Files and ...
    • Viewing and Editing...
    • Managing Processes ...
    • Scheduling Tasks wi...
    • Disk Usage Analysis...
    • File and Directory ...
Blogs
  • Blogs
    • Free Hosting on AWS...
    • PHP 8.6 Partial Fun...
    • What is SEO?
    • Zoho Free Mail
    • Speed Up Your Appli...
    • What is a JavaScrip...
    • Laravel vs Lumen: T...
    • MySQL vs PostgreSQL...
    • Automate Free MySQL...
    • How to Use Google A...
    • What is n8n?
    • Cloud Platform Comp...
    • Top Common Mistakes...
    • PHP 8.5: The Pipeli...
    • Google Antigravity ...
    • How to Optimize Que...
    • React vs Angular vs...
    • Base44: Features, P...
    • Difference Between ...
    • HTTP Status Codes E...
    • Build Native Mobile...
    • Top 10 JavaScript F...
    • JIRA, Waterfall, an...
    • WebSockets in Moder...
    • A Complete Real-Wor...
    • Why Developers Shou...
    • Service-Based Compa...
    • Bootstrap vs Tailwi...
    • Direct Prompt vs St...
    • Top 25 SEO HTML Tag...
    • Docker Commands Che...
    • Authentication vs A...
    • Top AI Portals in 2...
    • What is Replit? Com...
    • Laravel 13 Released...
    • NEET Paper Leak Pre...