본문으로 건너뛰기

저장 뒤 다른 쪽으로

Next.js 목차 서버 함수 레슨 30 / 47

목차

redirect는 next/navigation의 함수로, 서버 함수 안에서 부르면 브라우저를 다른 주소로 보냅니다. 이 레슨은 createRecipe가 저장에 성공하면 새 레시피 쪽 /recipes/<새 id>로 보내게 하고, redirect 다음 줄과 try 안에서 생기는 일을 서버 터미널로 봅니다.

지금은 더하기에 성공해도 화면은 폼 그대로입니다. 더한 레시피를 보려면 목록으로 가서 찾아야 합니다. 저장한 서버 함수는 새 레시피의 id를 아니, 그 쪽으로 바로 보내면 됩니다.

1저장한 뒤 redirect 부르기

app/actions.ts 맨 위에서 next/navigation의 redirect를 가져오고, updateTag 다음 줄에서 부릅니다.

app/actions.ts
…
  // 3. 저장하기
  const recipe =
    await addRecipe({
…
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}
…
  • addRecipe는 더한 레시피를 돌려줍니다(서버 함수에서 끝에 둔 return recipe). 그 id로 새 쪽 주소를 만듭니다.
  • 성공하면 쪽을 옮기니 끝의 return { error: '' }는 지웁니다. 메시지는 검사에 걸린 때만 돌려줍니다.
  • 이로써 서버 함수의 차례 다섯이 다 찼습니다. 1. 폼에 서버 함수 달기 → 2. 값 꺼내 검사하기 → 3. 저장하기 → 4. 기억 지우기 → 5. 새 쪽으로 보내기.

탭을 닫은 채 저장했으면 차례대로 합니다.

  1. 새 탭의 주소 칸에 /recipes를 쳐서 목록을 한 번 엽니다.
  2. 같은 탭에서 /recipes/new를 열고 이름 크림 파스타, 분류 양식, 분 20을 넣고 '더하기'를 누릅니다.
app/actions.ts 전체 · 옮겨 간 화면 · 서버 터미널

아래는 고친 app/actions.ts, 2 뒤의 화면, 서버 터미널입니다. 시간과 주소의 긴 글자는 다를 수 있습니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><h2>크림 파스타</h2><section><button>재료 보기</button></section></section><footer>바닥글</footer>
결과 화면
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 214ms
✓ Running next.config.ts took 1021ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 163ms (next.js: 61ms, application-code: 102ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
더하기 쪽을 그림
 GET /recipes/new 200 in 31ms (next.js: 10ms, application-code: 21ms)
레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 하나 읽음 a30b884b-0471-40bf-9880-23db8d837a53
레시피 파일 읽음
 Cache  레시피 하나 읽음 a30b884b-0471-40bf-9880-23db8d837a53
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/a30b884b-0471-40bf-9880-23db8d837a53 200 in 253ms (next.js: 4ms, generate-params: 225ms, application-code: 24ms)
 Cache  레시피 하나 읽음 a30b884b-0471-40bf-9880-23db8d837a53
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 a30b884b-0471-40bf-9880-23db8d837a53
 Cache  레시피 파일 읽음
 POST /recipes/new 200 in 429ms (next.js: 0.6ms, application-code: 428ms)
  └─ ƒ createRecipe({"error":""}, {}) in 2ms app/actions.ts

'더하기'를 누르자 주소가 /recipes/…로 바뀌고 크림 파스타 쪽이 열렸습니다. 서버 터미널에는 GET /recipes/… 줄이 POST /recipes/new 200⁠보다 먼저 찍혔습니다. '더하기'를 누른 뒤의 레시피 파일 읽음 · 레시피 하나 읽음 줄(Cache가 붙은 줄도)은 옮겨 갈 쪽을 그리며 찍힌 것이라 여기서는 세지 않습니다. JS로 보낸 폼이면 서버가 POST 안에서 옮겨 갈 쪽까지 그려 응답에 싣고, 브라우저는 그 응답으로 쪽을 옮깁니다(Next.js 문서 redirect — 'performs a client-side navigation'). 이것은 개발 판에서 JS로 보낸 폼을 잰 것입니다. JS를 끈 폼은 303 See Other 응답을 받아 브라우저가 새 주소를 GET으로 엽니다(Next.js 문서 redirect).

2redirect 다음 줄

redirect 다음 줄에 console.log('끝');을 넣고 탭을 닫은 채 저장합니다. 새 탭으로 목록을 한 번 연 뒤 같은 탭에서 /recipes/new를 열어 떡볶이(분 30)를 더합니다. 서버 터미널에 끝이 찍힐까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 찍힌다 — redirect는 갈 주소만 정해 두고 함수는 끝까지 돈다
  • ② 찍히고, 쪽은 옮겨 가지 않는다
  • ③ 찍히지 않는다 — redirect가 던져 함수가 그 자리에서 멈춘다
결과 보기

③입니다. 아래는 1절의 app/actions.ts, console.log('끝');을 넣은 판, 떡볶이를 더하기까지 마친 서버 터미널입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };
app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
  console.log('끝');
}

export { createRecipe };
실행 결과
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 214ms
✓ Running next.config.ts took 999ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 173ms (next.js: 63ms, application-code: 110ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
더하기 쪽을 그림
 GET /recipes/new 200 in 31ms (next.js: 10ms, application-code: 21ms)
레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 하나 읽음 86e9055d-4bf3-4e54-b900-6c5a60ab34a2
레시피 파일 읽음
 Cache  레시피 하나 읽음 86e9055d-4bf3-4e54-b900-6c5a60ab34a2
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/86e9055d-4bf3-4e54-b900-6c5a60ab34a2 200 in 257ms (next.js: 3ms, generate-params: 231ms, application-code: 23ms)
 POST /recipes/new 200 in 408ms (next.js: 1.5ms, application-code: 406ms)
  └─ ƒ createRecipe({"error":""}, {}) in 3ms app/actions.ts
 Cache  레시피 하나 읽음 86e9055d-4bf3-4e54-b900-6c5a60ab34a2
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 86e9055d-4bf3-4e54-b900-6c5a60ab34a2
 Cache  레시피 파일 읽음

터미널에 끝이 없습니다(옮겨 간 쪽을 그린 줄은 1절과 같은 꼴입니다). redirect는 Next.js만 아는 오류 NEXT_REDIRECT를 던집니다(Next.js 문서 redirect — 'throws a NEXT_REDIRECT error'). 던진 줄 아래는 돌지 않고, Next.js가 그 오류를 받아 응답을 새 쪽으로 바꿉니다.

다 봤으면 console.log('끝'); 줄을 지우고 저장합니다. redirect 아래에 둔 줄은 돌지 않으니, updateTag는 redirect보다 앞에 둡니다(Next.js 문서 Server Actions — 'Place revalidation calls before redirect').

해 보기 — redirect를 try 안으로

redirect(…)를 try로 감싸고, catch에서 잡은 것을 찍어 봅니다. 함수 끝에는 return { error: '' };⁠를 다시 둡니다.

app/actions.ts
…
  // 5. 새 쪽으로 보내기
  try {
    redirect(
      '/recipes/' + recipe.id,
    );
  } catch (e) {
    console.log(
      '잡힘',
      String(e),
    );
  }
  return { error: '' };
}
…

탭을 닫은 채 저장하고, 새 탭으로 목록을 한 번 연 뒤 같은 탭에서 /recipes/new를 열어 계란국(분 15)을 더합니다. 어떻게 될까요? 고른 뒤 펼쳐 보세요.

  • ① 새 레시피 쪽으로 옮겨 간다
  • ② 폼에 그대로 머문다 — catch가 던진 것을 잡았다
  • ③ 오류 쪽이 뜬다
결과 보기

②입니다. 아래는 try로 감싼 app/actions.ts, 더한 뒤의 화면, 서버 터미널입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  try {
    redirect(
      '/recipes/' + recipe.id,
    );
  } catch (e) {
    console.log(
      '잡힘',
      String(e),
    );
  }
  return { error: '' };
}

export { createRecipe };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" enctype="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_1"><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;600f316624eb6fb6d22dfc103dc2d1ae1d9bc18c5b&quot;,&quot;bound&quot;:&quot;$@1&quot;}"><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;&quot;}]"><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"><input placeholder="이름" name="title"><select name="category" aria-label="분류"><option selected="">한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"><button>더하기</button><p></p></form></section><footer>바닥글</footer>
결과 화면
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 209ms
✓ Running next.config.ts took 991ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 177ms (next.js: 59ms, application-code: 118ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
더하기 쪽을 그림
 GET /recipes/new 200 in 30ms (next.js: 10ms, application-code: 20ms)
잡힘 Error: NEXT_REDIRECT
더하기 쪽을 그림
 POST /recipes/new 200 in 28ms (next.js: 2ms, application-code: 26ms)
  └─ ƒ createRecipe({"error":""}, {}) in 3ms app/actions.ts

catch가 NEXT_REDIRECT를 잡아 잡힘 Error: NEXT_REDIRECT⁠가 찍혔고, 함수는 이어 돌아 { error: '' }를 돌려줬습니다. 오류가 Next.js에 닿지 않아 쪽은 폼 그대로입니다. 저장과 updateTag는 그 앞에서 이미 돌았습니다. 터미널의 둘째 더하기 쪽을 그림이 그 표시입니다.

다 봤으면 try를 풀어 1절의 app/actions.ts로 되돌리고 저장합니다.

예제

1절의 app/actions.ts에서 updateTag('recipes'); 줄과 그 import를 빠뜨렸다고 합시다. 탭을 닫은 채 저장하고, 새 탭으로 목록을 한 번 연 뒤 같은 탭에서 /recipes/new를 열어 김밥(분 10)을 더하면, 옮겨 간 쪽은 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 없는 쪽이 보인다
  • ② 김밥 쪽이 보인다 — 새 주소는 기억에 없으니 새로 읽는다
  • ③ 목록 쪽으로 간다
결과 보기

①입니다. 아래는 1절의 app/actions.ts, 두 줄을 뺀 판, 옮겨 간 화면입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };
app/actions.ts
'use server';

import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><h1>없는 쪽</h1><p>주소를 확인하세요.</p><footer>바닥글</footer>
결과 화면

없는 쪽이 열렸습니다. 새 쪽의 getRecipe(id)는 처음 받는 id라 새로 돌지만, 그 안에서 부르는 getRecipes()는 목록을 한 번 열 때 기억한 목록을 줍니다. 그 목록에 방금 더한 김밥의 새 id가 없어 쪽이 notFound()로 갔습니다. updateTag가 있으면 이 기억이 지워져 새로 읽습니다.

다 봤으면 두 줄을 되살려 저장하고, data/recipes.json을 씨앗 넷으로 되돌립니다. 되돌린 뒤 개발 서버를 Ctrl+C로 끄고 npm run dev로 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: redirect 아래에 둔 줄도 돈다.

맞는 규칙: redirect는 NEXT_REDIRECT 오류를 던져 함수를 멈춥니다. 꼭 해야 할 일(updateTag 같은)은 redirect 앞에 둡니다.

틀린 생각: 저장이 실패할 때를 대비해 redirect까지 try로 감싸 둔다.

맞는 규칙: catch가 redirect의 오류까지 잡아 쪽이 옮겨 가지 않습니다. redirect는 try 밖에서 부릅니다(Next.js 문서 redirect — 'should be called outside the try block').

틀린 생각: 새 쪽은 새 주소라 기억과 상관없이 새 레시피가 보인다.

맞는 규칙: 레시피 쪽의 getRecipe는 기억한 getRecipes 목록에서 찾습니다. updateTag를 빠뜨리면 옛 목록에 새 레시피의 id가 없어 없는 쪽이 됩니다.

확인 문제

문제 1. createRecipe에서 redirect(…) 바로 아래 줄은 언제 돌까요?

  • ① 브라우저가 새 쪽을 다 연 뒤
  • ② 돌지 않는다
  • ③ redirect보다 먼저
정답

②입니다. redirect가 NEXT_REDIRECT를 던져 함수가 그 자리에서 멈춥니다.

  • ① 서버 함수는 브라우저를 기다렸다 이어 돌지 않습니다.
  • ③ 줄은 위에서 아래로 돕니다. 아래 줄이 먼저 돌 까닭이 없습니다.

문제 2. 아래처럼 쓰면 더하기를 눌러도 쪽이 옮겨 가지 않습니다. 까닭은 무엇일까요?

app/actions.ts
…
  try {
    redirect('/recipes');
  } catch (e) {
    console.log(e);
  }
  return { error: '' };
…
  • ① redirect는 try 안에서 부를 수 없어 빌드가 멈춰서
  • ② 주소가 틀려서
  • ③ catch가 redirect가 던진 오류를 잡아 삼켜서
정답

③입니다. Next.js는 던져진 NEXT_REDIRECT를 받아야 쪽을 옮깁니다. catch가 잡으면 그 오류가 Next.js에 닿지 않습니다.

  • ① 빌드는 지나갑니다. 오류 없이 옮겨 가지 않을 뿐입니다.
  • ② /recipes는 있는 주소입니다.

문제 3. updateTag('recipes')를 redirect 앞에 두는 까닭은 무엇일까요?

  • ① 옮겨 간 쪽이 새로 읽게, 기억을 먼저 지우려고
  • ② redirect가 updateTag를 부르니까
  • ③ 순서는 상관없다
정답

①입니다. redirect 아래에 두면 돌지 않아, 옮겨 간 쪽이 옛 목록에서 찾습니다.

  • ② redirect는 기억을 지우지 않습니다.
  • ③ redirect 아래 줄은 돌지 않으니 순서가 중요합니다.
이 레슨에서 바꾼 파일

app/actions.ts — redirect import · 저장한 레시피를 받아 // 5. 새 쪽으로 보내기 · 끝의 return 지움

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로