Skip to main content

Authentication Basics

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • Authentication vs authorization concepts
  • JWT tokens from ASP.NET Core API
  • Storing tokens in cookies or localStorage
  • Login/logout form patterns
  • Protected routes and middleware
  • NextAuth.js for session management
  • Refresh token rotation
  • SMS login flow and role-based access

Why This Matters

Authentication Basics is part of building production React applications with Next.js. You will use it when creating student dashboards, SEO-friendly pages, API-connected forms, route handlers, layouts, and deployments for .NET-backed systems.

Authentication answers: "Who is the current user?" Authorization answers: "What is this user allowed to do?"

In a .NET-centered architecture, ASP.NET Core often remains the authority for users, roles, permissions, and tokens.

The Problem

Beginners often treat Next.js like plain React and miss routing, rendering, server/client boundaries, environment variables, and deployment behavior. This lesson shows how Authentication Basics works in a real School Management System frontend that talks to ASP.NET Core APIs.

Common Architecture

Next.js UI
-> Login request
-> ASP.NET Core Auth API
-> JWT or secure cookie
-> Protected API calls

JWT Flow

  1. User enters username and password.
  2. Next.js sends credentials to ASP.NET Core.
  3. ASP.NET Core validates the user.
  4. ASP.NET Core returns a token or sets a secure cookie.
  5. Next.js uses that authentication state for protected screens.

Protected Client Request

async function loadProfile(token) {
const response = await fetch("/api/profile", {
headers: {
Authorization: `Bearer ${token}`
}
});

if (!response.ok) {
throw new Error("Unauthorized");
}

return response.json();
}

Middleware

Next.js middleware can redirect users before a page loads.

middleware.js
import { NextResponse } from "next/server";

export function middleware(request) {
const token = request.cookies.get("auth_token");

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

return NextResponse.next();
}

For many web apps, a secure HTTP-only cookie is safer than storing tokens in local storage.

ℹ️ Security preference

Prefer HTTP-only secure cookies for browser apps when possible. They reduce the risk of token theft through frontend JavaScript.

Role-Based UI

Frontend role checks improve user experience, but backend policy decides the truth.

function AdminOnlyButton({ user }) {
if (user.role !== "Admin") {
return null;
}

return <button>Delete Student</button>;
}
⚠️ Do not trust hidden buttons

Hiding a button is not authorization. ASP.NET Core must still reject unauthorized requests.

Interview Questions

🎯 Where should authorization be enforced?

Authorization must be enforced on the backend, usually in ASP.NET Core policies, controllers, minimal APIs, or endpoint filters.

🎯 Why avoid localStorage for sensitive tokens?

Tokens in localStorage can be read by JavaScript. If the page has an XSS issue, an attacker may steal the token.

Quick Definitions

  • Authentication Basics - The main Next.js concept explained in this lesson.
  • App Router - The modern Next.js routing system based on the app folder.
  • Server/Client boundary - The decision of whether code runs on the server or in the browser.
  • ASP.NET Core integration - Calling or proxying backend APIs from a Next.js frontend.

Common Mistakes

  • Treating every component as a Client Component without a reason
  • Forgetting environment variables differ between local and production
  • Calling ASP.NET Core APIs from the browser without handling CORS
  • Putting secrets in NEXT_PUBLIC_ variables
  • Skipping npm run build before deployment

Practice Task

Create a small Next.js example using Authentication Basics. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Create or update a route, layout, form, or data-fetching example.
  2. Use realistic student, teacher, attendance, or marks data.
  3. Connect the example to an ASP.NET Core-style API URL or route handler.
  4. Add one loading, empty, or error state where relevant.
  5. Explain what runs on the server and what runs in the browser.

Quick Revision

QuestionAnswer
What is the main idea?Use Authentication Basics correctly in a Next.js App Router project.
Where is it used?Pages, layouts, route handlers, forms, APIs, authentication, and deployment.
What should beginners watch carefully?Server/client boundaries, environment variables, CORS, and production builds.
What is the best debugging habit?Check terminal build output, browser console, network tab, and server logs.
🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

Use ChatGPT, Claude, or Copilot to go deeper on Authentication Basics. Try these prompts:

  • "Explain Authentication Basics with a Next.js and ASP.NET Core example"
  • "Give me 5 practice tasks for Authentication Basics in a School Management app"
  • "Show common Next.js mistakes in Authentication Basics and how to fix them"
  • "Quiz me on Authentication Basics with interview-style questions"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

Deployment ->

nexcoding.in