6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】サーバーコンポーネントで現在のURLを取得する方法

Last updated at Posted at 2023-10-21

以下のようにするとサーバーコンポーネントで現在のURLを取得できます。

middleware.ts
import { NextResponse } from 'next/server'
import { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  const requestHeaders = new Headers(req.headers)
  requestHeaders.set('x-url', req.url)

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    }
  })
}

layout.tsx
import { headers } from 'next/headers';

export default function RootLayout() {
  const headersList = headers()
  const header_url = headers().get('x-url') || "";
}

パスを取得するには以下のようにします。

middleware.ts
import { NextResponse } from 'next/server'
import { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  const requestHeaders = new Headers(req.headers)
  requestHeaders.set('x-pathname', req.nextUrl.pathname)

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    }
  })
}

layout.tsx
import { headers } from 'next/headers';

export default function RootLayout() {
  const headersList = headers()
  const pathname = headers().get('x-pathname') || "";
}
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?