
Adding Authentication Context to Next.js App Router with JWT
By Sharan Panthi
#next.js#app router#auth#auth context#auth state#context api#useContext
This article builds on a previous setup for JWT-based authentication with HTTP-only cookies in a Next.js application using the App Router. We'll create an authentication context to manage user authentication state and provide easy access to user data and authentication methods across the app.
Prerequisites
- A Next.js project with JWT authentication and HTTP-only cookies, as described in the previous article.
- Familiarity with React Context API and TypeScript.
Step 1: Setting Up the Authentication Context
Create a context to manage the authentication state and provide methods for login and logout.
File: app/context/AuthContext.tsx
'use client';
import {
createContext,
useContext,
useState,
useEffect,
ReactNode,
} from 'react';
import { useRouter } from 'next/navigation';
import jwt from 'jsonwebtoken';
// Define types for the user and context
interface User {
userId: number;
email: string;
}
