본문으로 건너뛰기

얼마나 기억하나

Next.js 목차 미리 그리기와 캐시 레슨 24 / 47

목차

cacheLife는 'use cache'로 기억한 결과를 얼마나 쓸지 정하는 함수입니다. 이 레슨은 cacheLife('hours')가 정하는 세 수 stale · revalidate · expire를 빌드 출력의 1h · 1d 칸과 배포 판 응답 머리 Cache-Control에 짝짓고, 기한이 지난 뒤 첫 요청이 무엇을 받는지 봅니다.

'use cache'의 목록은 데이터 파일을 고쳐도 넷 그대로였습니다. 기억한 목록은 언제까지 쓰일까요? 'hours'라는 이름만으로는 한 시간 뒤에 무슨 일이 생기는지 알 수 없습니다.

1'hours'의 세 수

cacheLife에 넘기는 'hours'는 이름 붙은 묶음(프로필)이고, 세 수를 한꺼번에 정합니다(Next.js 문서 cacheLife).

수'hours'
stale5분
revalidate1시간
expire1일
  • stale — 브라우저가 서버에 묻지 않고 기억한 것을 쓰는 기한('How long the client can use cached data without checking the server')
  • revalidate — 지나면 다음 요청이 뒤에서 다시 읽기를 시작하게 하는 기한('the next request will trigger a background refresh'). 판마다 다른 것은 자주 틀리는 곳 첫째에서 봅니다
  • expire — 요청 없이 이만큼 지나면, 다음 요청은 새로 읽기를 기다리게 되는 기한('the next one waits for fresh content')
프로필 일곱 개

Next.js 문서 cacheLife의 프로필 표를 옮긴 것입니다. 이름을 넘기지 않으면 default입니다.

프로필stalerevalidateexpire
default5분15분없음
seconds30초1초1분
minutes5분1분1시간
hours5분1시간1일
days5분1일1주
weeks5분1주30일
max5분30일1년

2빌드 출력과 응답 머리

개발 서버를 Ctrl+C로 끄고 npm run build를 친 뒤, npm run start로 띄워 /stats의 응답 머리를 봅니다. 파일은 앞 레슨 끝 그대로입니다.

lib/recipes.ts 전체 · 빌드 출력 · 응답 머리

아래는 앞 레슨 끝 그대로의 lib/recipes.ts, 빌드 출력, 배포 판 /stats의 응답 머리입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
  Creating an optimized production build ...
✓ Compiled successfully in 3.1s
  Running TypeScript ...
  Finished TypeScript in 1499ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 344ms
  Generating static pages using 8 workers (0/11) ...
레시피 파일 읽음
  Generating static pages using 8 workers (2/11)
  Generating static pages using 8 workers (5/11)
  Generating static pages using 8 workers (8/11)
✓ Generating static pages using 8 workers (11/11) in 492ms
  Finalizing page optimization ...
✓ Finalizing page optimization in 11ms

Route (app)            Revalidate  Expire
┌ ◐ /                          1h      1d
├ ○ /_not-found
├ ◐ /recipes
├   /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ○ /recipes/r1              1h      1d
│ ├ ○ /recipes/r2              1h      1d
│ └ ◐ [+2 more paths]
└ ○ /stats                     1h      1d


○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content
HTTP/1.1 200 OK
x-nextjs-cache: HIT
x-nextjs-prerender: 1
x-nextjs-prerender: 1
Cache-Control: s-maxage=3600, stale-while-revalidate=82800
Content-Type: text/html; charset=utf-8

경로 표의 Revalidate 칸 1h가 revalidate 1시간, Expire 칸 1d가 expire 1일입니다. 응답 머리의 Cache-Control도 같은 두 수를 초로 적습니다. s-maxage=3600은 revalidate 3600초(1시간)이고, stale-while-revalidate=82800⁠은 expire에서 revalidate를 뺀 82800초(23시간)입니다(Next.js 소스 server/lib/cache-control.js⁠가 expire − revalidate로 셈). revalidate가 지난 뒤 expire까지는 옛 것을 주면서 뒤에서 새로 읽어도 된다는 뜻입니다.

stale 5분은 이 머리에 없습니다. stale은 브라우저 쪽 기한이라, 서버가 다른 머리 x-nextjs-stale-time으로 따로 알립니다(Next.js 문서 cacheLife — 'The stale property controls the Client Cache, not the Cache-Control header').

해 보기 — 'seconds'로 바꿔 보기

revalidate 1시간은 기다려 보기에 깁니다. revalidate가 1초인 'seconds'로 바꿔, 개발 판에서 기한이 지난 뒤 첫 요청을 봅니다. 배포 판을 끄고 npm run dev로 개발 서버를 띄운 뒤 차례대로 합니다. 목록 쪽 RecipeList가 <Suspense> 안에 있는지 먼저 봅니다(서버에서 읽기에서 감싼 그대로입니다).

  1. 주소 칸에 /recipes를 쳐서 목록을 한 번 엽니다. 이 탭은 해 보기 끝까지 열어 둡니다.
  2. lib/recipes.ts의 cacheLife('hours')를 cacheLife('seconds')로 바꿔 저장합니다.
  3. 목록을 한 번 엽니다.
  4. data/recipes.json에 'use cache' 해 보기의 된장찌개를 더하고 저장합니다.
  5. 몇 초 뒤(1분 안에) 목록을 새로 고칩니다.
  6. 터미널에 꼬리표 없는 레시피 파일 읽음이 찍힌 것을 보고, 조금 뒤 다시 새로 고칩니다.
  7. data/recipes.json에서 더한 레시피를 지워 넷으로 되돌린 뒤, cacheLife('seconds')를 cacheLife('hours')로 되돌려 저장하고 목록을 새로 고칩니다.
lib/recipes.ts
…
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('seconds');
…
바꾼 파일 · 화면

아래는 차례대로 1의 lib/recipes.ts('hours' 판), 2에서 바꾼 lib/recipes.ts, 4에서 레시피를 더한 data/recipes.json, 5와 6에서 새로 고친 목록의 화면에 보이는 <body> 안 HTML, 7에서 되돌린 data/recipes.json · lib/recipes.ts, 그 뒤 새로 고친 목록의 화면입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('seconds');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  },
  {
    "id": "r5",
    "title": "된장찌개",
    "category": "한식",
    "minutes": 20,
    "ingredients": [
      "된장",
      "두부"
    ],
    "favorite": false
  }
]
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></section><footer>바닥글</footer>
결과 화면
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li><li><a href="/recipes/r5">된장찌개</a><button>☆</button></li></ul></section><footer>바닥글</footer>
결과 화면
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  }
]
lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></section><footer>바닥글</footer>
결과 화면

2에서 코드 파일을 고쳐 저장하면 개발 서버가 기억을 지웁니다('use cache' 해 보기의 결과 보기). 목록 탭을 열어 둔 채라 개발 서버가 그 쪽을 스스로 다시 받고, 기억은 곧바로 옛 목록으로 다시 찹니다. 탭을 닫았다면 3에서 목록을 열 때 기억이 다시 찹니다. 어느 쪽이든 데이터를 바꾸기 전에 기억에는 옛 목록이 듭니다.

5의 목록은 아직 옛 목록 넷입니다. 개발 서버는 revalidate 1초가 지났어도 기억해 둔 것을 한 번 더 주고, 뒤에서 다시 읽기를 시작합니다. 그때 꼬리표 없는 레시피 파일 읽음이 찍힙니다. 다시 읽기를 시작했다는 표시이고, 끝났다는 표시는 아닙니다. 다시 읽기가 끝난 뒤 연 6의 목록에서 된장찌개가 보입니다. 바로 안 바뀌면 한 번 더 새로 고칩니다.

7은 데이터를 먼저 되돌립니다. 그 뒤 코드 파일을 고쳐 저장하면 기억이 지워져, 목록이 넷으로 새로 읽힙니다. 단원 6은 'hours'와 레시피 넷에서 시작합니다.

예제

cacheLife('hours') 그대로 배포 판으로 봅니다. 개발 서버를 끄고 npm run build → npm run start로 띄운 뒤 /recipes를 한 번 엽니다. 그다음 data/recipes.json에 된장찌개를 더하고, 처음 연 뒤 10분 안에 /recipes를 다시 엽니다. 기다릴 것 없이 곧바로 열어도 됩니다. 목록은 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 된장찌개까지 다섯 — stale 5분이 지났으니까
  • ② 넷 그대로 — revalidate 1시간이 아직 안 지났으니까
  • ③ 된장찌개까지 다섯 — 데이터 파일을 고치면 기억이 지워지니까
결과 보기

②입니다. 아래는 앞 레슨 끝 그대로의 lib/recipes.ts, 처음 연 목록의 받은 HTML(다듬음), 레시피를 더한 data/recipes.json, 몇 초 뒤 다시 연 목록의 받은 HTML입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"/><button>찾기</button></form><template id="B:0"></template><p>목록을 읽는 중</p></section><footer>바닥글</footer><div hidden id="S:0"><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></div>
결과 화면
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  },
  {
    "id": "r5",
    "title": "된장찌개",
    "category": "한식",
    "minutes": 20,
    "ingredients": [
      "된장",
      "두부"
    ],
    "favorite": false
  }
]
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"/><button>찾기</button></form><template id="B:0"></template><p>목록을 읽는 중</p></section><footer>바닥글</footer><div hidden id="S:0"><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></div>
결과 화면

상자는 몇 초 뒤에 연 것이고, 10분 뒤에 열어도 넷 그대로입니다. 서버는 revalidate 1시간이 지나기 전에는 다시 읽지 않습니다. stale 5분은 브라우저 쪽 기한이라 서버가 다시 읽는 때와 상관이 없습니다. 데이터 파일을 고쳐도 기억은 지워지지 않습니다.

다 봤으면 배포 판을 끄고 data/recipes.json을 레시피 넷으로 되돌린 뒤 npm run dev로 개발 서버를 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: revalidate가 다 되면, 요청이 없어도 서버가 그때 스스로 다시 읽어 기억을 새 목록으로 바꿔 둔다.

맞는 규칙: 서버는 revalidate가 지난 뒤 처음 온 요청에서 움직입니다. 그 요청이 받는 것은 판마다 다릅니다. 개발 판은 기억해 둔 옛 목록을 한 번 더 주고 뒤에서 다시 읽습니다. 새 목록은 다시 읽기가 끝난 뒤의 요청부터입니다(해 보기 5 · 6). 배포 판의 기본 기억 칸(서버 메모리)은 revalidate가 지난 기억을 버려, 그 요청이 새로 읽기를 기다려 새 목록을 받습니다. 쪽 전체를 미리 그려 둔 ○ 쪽(/stats)은 2절 응답 머리의 뜻대로 옛 쪽을 한 번 더 주고 뒤에서 다시 그립니다(그 응답 머리는 x-nextjs-cache: STALE).

틀린 생각: stale 5분이 지나면 서버가 다시 읽는다.

맞는 규칙: stale은 브라우저가 서버에 묻지 않고 쓰는 기한입니다. 서버가 다시 읽는 때는 revalidate가 정합니다(예제).

틀린 생각: 개발 판 터미널에 꼬리표 없는 레시피 파일 읽음이 찍혔으니, 그 요청은 새로 읽은 목록을 받았다.

맞는 규칙: 개발 판에서 revalidate가 지난 뒤 찍힌 그 줄은 뒤에서 다시 읽기를 시작했다는 표시입니다. 그 요청이 받은 것은 옛 목록 넷이었습니다(해 보기 5).

확인 문제

문제 1. cacheLife('hours')의 revalidate는 얼마일까요?

  • ① 5분
  • ② 1시간
  • ③ 1일
정답

②입니다. 빌드 출력 경로 표의 Revalidate 칸 1h가 이 수입니다.

  • ① 5분은 stale입니다.
  • ③ 1일은 expire입니다(Expire 칸 1d).

문제 2. 배포 판 응답 머리 Cache-Control 줄의 s-maxage=3600에서 3600은 어느 수를 초로 적은 것일까요?

  • ① stale 5분
  • ② expire 1일
  • ③ revalidate 1시간
정답

③입니다. 3600초가 1시간입니다.

  • ① stale은 브라우저 쪽 기한이라 이 머리에 없습니다.
  • ② 82800이 expire 1일(86400초)에서 revalidate를 뺀 수입니다.

문제 3. 개발 서버를 띄워 둔 채, cacheLife('hours')로 목록을 기억한 뒤 레시피 보관함의 어느 쪽도 열지 않고 이틀이 지났습니다. 다음 요청은 무엇을 받을까요?

  • ① 옛 목록 — 받은 뒤 서버가 뒤에서 다시 읽는다
  • ② 새로 읽은 목록 — 새로 읽기가 끝날 때까지 기다린다
  • ③ 빈 목록 — 기억이 지워져 보일 것이 없다
정답

②입니다. expire 1일이 지났으니, 다음 요청은 새로 읽기를 기다립니다(Next.js 문서 cacheLife — 'the next one waits for fresh content'). 배포 판이어도 답은 같습니다. 배포 판은 revalidate 1시간이 지난 기억을 버리기 때문입니다(자주 틀리는 곳 첫째).

  • ① 개발 판에서 옛 것을 주며 뒤에서 다시 읽는 것은 revalidate가 지나고 expire는 안 지난 때입니다(해 보기 5).
  • ③ 기다리는 동안 비워 두지 않고, 새로 읽은 목록을 줍니다.

이 레슨은 고친 것을 모두 되돌려, 바꾼 파일이 없습니다. 다음 레슨은 인자가 있는 함수 getRecipe(id)를 기억시킵니다.

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

Next.js 목차로