環境
- Next.js v15
 
- React v18
 
- App Router
 
Page.tsx で取得する
import { headers } from "next/headers"
function findClientIPAddress(str: string): string {
	let arr: string[] = str.split(", ")
	let res = ""
	if (arr.length > 0) {
		res = arr[0]
		arr = res.split(":")
		if (arr.length > 0) {
			res = arr[arr.length - 1]
		}
	}
	return res
}
export default async function Page() {
	const H = await headers()
	const ipAddress = findClientIPAddress(H.get("X-Forwarded-For"))
	const userAgent = H.get("user-agent")
	return (
		<>
			IPアドレス: {ipAddress}<br/>
			userAgent: {userAgent}<br/>
		<>
	)
}
middleware.ts で取得する
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
function findClientIPAddress(str: string): string {
	let arr: string[] = str.split(", ")
	let res = ""
	if (arr.length > 0) {
		res = arr[0]
		arr = res.split(":")
		if (arr.length > 0) {
			res = arr[arr.length - 1]
		}
	}
	return res
}
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
	const response = NextResponse.next()
	let ipAddress = "unknown"
	let userAgent = "unknown"
	
	if (request.headers.get("X-Forwarded-For")) {
		ipAddress = findClientIPAddress(request.headers.get("X-Forwarded-For"))
	}
	if (request.headers.get("user-agent")) {
		userAgent = request.headers.get("user-agent")
	}
	response.cookies.set({
		name: "ipAddress",
		value: ipAddress,
		path: "/",
		maxAge: 60 * 5, // 5分,
	})
	response.cookies.set({
		name: "userAgent",
		value: userAgent,
		path: "/",
		maxAge: 60 * 5, // 5分,
	})
	console.log(ipAddress)
	console.log(userAgent)
	return response
}
// See "Matching Paths" below to learn more
export const config = {
	matcher: "/((?!api|assets|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
}