Project/foliohub

[Next.js] NotFound / Error 페이지 Custom하기

솔B 2024. 4. 6. 20:07

Next.js에서는 아래와 같은 NotFound 페이지를 기본적으로 제공한다.

NotFound 페이지는 사용자가 존재하지 않는 url에 진입 시 나타나는 페이지로, 사용자의 이탈을 막고 정상적인 페이지로 유도하기 위해 이를 적절하게 활용하는 것이 사용자 경험에 도움이 된다.

 

Next.js에서 NotFound와 Error 페이지를 간단하게 커스텀 할 수 있는데

이번 글에서는 이를 다루는 방법에 대해서 알아보겠다!

 

NotFound 페이지

나의 경우엔

- 없는 페이지 경로로 진입 시

- 존재하지 않는 username로 포트폴리오 상세 페이지(/[username]) 진입 시

두가지 경우에 NotFound 처리가 필요했다.

 

not-found.tsx 생성하기

간단하게 에러문구와 메인으로 돌아갈 수 있는 버튼을 추가했다.

app/not-found.tsx

import { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'Foliohub - NotFound',
  robots: 'noindex',
}

export default function NotFound() {
  return (
    <>
      <div className="flex flex-col items-center justify-center mt-32">
        <h1>404 ERROR</h1>
        <p className="body1 text-gray-400 mt-4 mb-10">
          해당 페이지를 찾을 수 없어요!
        </p>
        <a
          href="/"
          className="flex items-center justify-center rounded-full bg-black text-white h-12 px-8"
        >
          <span>메인으로 돌아가기</span>
        </a>
      </div>
      <div className="fixed bottom-80 left-10 rotate-[80deg]">
        <div className="animate-wave1 wave bg-[#42A7E3]" />
        <div className="animate-wave2 wave bg-[#5090E6]" />
        <div className="animate-wave3 wave bg-[#607AE9]" />
      </div>
    </>
  )
}

(너무 밋밋해 보여서 나름 파도 애니메이션 효과를 추가했다 ㅎㅎ)

이렇게 해주면 없는 "페이지 경로로 진입 시"에는 NotFound 화면으로 잘 이동한다!

 

notFound()

그럼 다음 경우를 처리 해보자 (존재하지 않는 username로 포트폴리오 상세 페이지(/[username]) 진입 시)

나는 각각 사용자의 포트폴리오 상세 페이지 url이 /[username] 이었기 때문에 /hello로 이동하면 포트폴리오 상세 페이지로 인식하고

해당 페이지가 실행되었다. 이걸 어찌 해야하나 했는데 엄청 간단하게 구현할 수 있는 함수가 있었다! ✨

 

next/navigation에 notFound()를 이용해 서버단에서 포트폴리오가 존재하지 않는다면 NotFound 페이지로 이동시켰다.

import Portfolio from '@/containers/portfolio/Portfolio'
import { fetchPortfolio } from '@/fetch/fetchPortfolio'
import { Metadata } from 'next'
import { notFound } from 'next/navigation'

type Props = {
  params: { username: string }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { username } = params
  const portfolio = await fetchPortfolio(username)
  if (!portfolio) {
    return notFound()
  }

  const metadata: Metadata = {
	...
  }

  return metadata
}

export default function UserPage({ params }: { params: { username: string } }) {
  return <Portfolio username={params.username} />
}

 

Error 페이지

error.tsx 생성하기

예기치 않은 오류가 발생했을 때 실행되며 반드시 클라이언트 컴포넌트(use client)로 만들어야 한다!

app/error.tsx

'use client'

import React from 'react'

function ErrorPage() {
  return (
    <>
      <div className="flex flex-col items-center justify-center mt-32">
        <h1>ERROR</h1>
        <p className="body1 text-gray-400 mt-4 mb-10">
          예상치 못한 오류가 발생했어요!
        </p>
        <a
          href="/"
          className="flex items-center justify-center rounded-full bg-black text-white h-12 px-8"
        >
          <span>메인으로 돌아가기</span>
        </a>
      </div>
      <div className="fixed bottom-80 left-10 rotate-[80deg]">
        <div className="animate-wave1 wave bg-[#42A7E3]" />
        <div className="animate-wave2 wave bg-[#5090E6]" />
        <div className="animate-wave3 wave bg-[#607AE9]" />
      </div>
    </>
  )
}

export default ErrorPage

 

Next.js 기능을 활용해 간단하게 NotFound와 Error 페이지 처리를 해봤다. Next.js에 정말 많은 기능이 있는데 더 알아보고 어서 프로젝트에 적용해보고 싶다 ㅎㅎ👍

참고자료

 

File Conventions: error.js | Next.js

API reference for the error.js special file.

nextjs.org

 

 

Functions: notFound | Next.js

API Reference for the notFound function.

nextjs.org