티스토리 뷰

서버

서버에서 현재 URL 정보를 가져오는 방법

import { headers } from 'next/headers'

export default async function Page() {
  const headersList = headers()
  const domain = headersList.get('host')
  const fullUrl = headersList.get('referer')

  return (
    <div>
      <p>Domain: {domain}</p>
      <p>Full URL: {fullUrl}</p>
    </div>
  )
}

클라이언트

클라이언트에서 가져오는 방법

'use client'
import { usePathname, useSearchParams } from 'next/navigation'

export default function Page() {
  const pathname = usePathname()
  const searchParams = useSearchParams()

  const fullUrl = `${pathname}?${searchParams}`

  return <div>Current URL: {fullUrl}</div>
}

위에 방법을 이용해서 필요한 URL 처리를 해보자.

예시)

// app/url-display/page.tsx
'use client'

import { usePathname, useSearchParams } from 'next/navigation'
import { useState } from 'react'

export default function UrlDisplayPage() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [newParam, setNewParam] = useState('')
  const [newValue, setNewValue] = useState('')

  // 현재 URL 생성
  const currentUrl = searchParams.toString() 
    ? `${pathname}?${searchParams}`
    : pathname

  // SearchParams를 객체로 변환
  const paramsObject: { [key: string]: string } = {}
  searchParams.forEach((value, key) => {
    paramsObject[key] = value
  })

  // 새 파라미터 추가를 위한 URL 생성 함수
  const createNewUrl = () => {
    if (!newParam || !newValue) return

    const newSearchParams = new URLSearchParams(searchParams.toString())
    newSearchParams.set(newParam, newValue)

    return `${pathname}?${newSearchParams.toString()}`
  }

  return (
    <div className="p-8 max-w-2xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">URL 정보 표시</h1>

      <div className="mb-6 p-4 bg-gray-100 rounded">
        <h2 className="font-semibold mb-2">현재 URL:</h2>
        <code className="block p-2 bg-white rounded">{currentUrl}</code>
      </div>

      <div className="mb-6">
        <h2 className="font-semibold mb-2">현재 Query Parameters:</h2>
        {Object.keys(paramsObject).length > 0 ? (
          <ul className="list-disc pl-5">
            {Object.entries(paramsObject).map(([key, value]) => (
              <li key={key} className="mb-1">
                <code>{key}: {value}</code>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-gray-500">No query parameters</p>
        )}
      </div>

      <div className="mb-6">
        <h2 className="font-semibold mb-4">새 Parameter 추가</h2>
        <div className="flex gap-4 mb-2">
          <input
            type="text"
            value={newParam}
            onChange={(e) => setNewParam(e.target.value)}
            placeholder="Parameter 이름"
            className="border p-2 rounded"
          />
          <input
            type="text"
            value={newValue}
            onChange={(e) => setNewValue(e.target.value)}
            placeholder="값"
            className="border p-2 rounded"
          />
        </div>
        <div>
          {newParam && newValue && (
            <div className="mt-2">
              <p className="text-sm text-gray-600">새로운 URL:</p>
              <code className="block p-2 bg-gray-100 rounded">{createNewUrl()}</code>
              <a
                href={createNewUrl()}
                className="inline-block mt-2 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
              >
                이 URL로 이동
              </a>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함