1.0.2 • Published 5 months ago
basnet v1.0.2
Middleware for Redirecting Based on Cookies
Overview
This middleware is designed for a Next.js application. It checks for a cookie named username
and redirects the user to a specific URL if the cookie's value matches a predefined condition.
Functionality
- Retrieves cookies from the request using
next/headers
. - Checks if the
username
cookie exists and its value. - If the username is
"basnet"
, the middleware redirects the user tohttps://linktr.ee/basnet
. - If the condition is not met, the request proceeds as normal.
Code Implementation
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function middleware() {
const cookie = await cookies();
const username = cookie.get("username")?.value;
if (username === "basnet") {
return NextResponse.redirect("https://linktr.ee/basnet");
}
return NextResponse.next();
}
Usage
Quick Setup with npx basnet
To use this middleware in your Next.js project, you can easily set it up with the following command:
npx basnet
This will automatically add the middleware to your project, checking for the username
cookie and redirecting users based on its value.
Manual Setup (Optional)
- Ensure that the
username
cookie is being set somewhere in your application. - The middleware will automatically check the cookie when a request is made.
- If the condition is met, the user is redirected; otherwise, the request proceeds normally.
Requirements
- Next.js 13 or newer
next/headers
andnext/server
modules
Notes
- Middleware runs on the Edge runtime.
- Ensure that the cookie is properly set and accessible by the middleware.
- Modify the redirect URL or conditions as needed to fit your application's logic.