Skip to content

Qvil Blog

[Next.js] Integrate date-fns i18n

Next.js, date-fns, i18n1 min read

Next.js에 date-fns를 적용할 때 Server와 Client환경 모두 설정을 해줘야한다.

0. Setup Next.js

Internationalized Routing 을 사용한다면

next.config.js

1module.exports = {
2 i18n: {
3 locales: ["ko", "en"],
4 defaultLocale: "ko",
5 },
6};

1. Create custom format function

date-fns의 i18n 문서(Check version!)를 참고하면 아래와 같이 date-fns의 format function을 customizing해서 사용하는 방식이다.

Global object의(Browser: window/Node.js: global) custom property를 사용하므로 declare 해줘야한다. 참고: [Typescript] declare custom property type of global object(window/global)

date.ts

1import { format as fnsFormat, Locale } from "date-fns";
2import { ko, enUS } from "date-fns/locale";
3
4type DateType = number | Date;
5
6const locales: Record<string, Locale> = { ko, enUS };
7
8// by providing a default string of 'PP' or any of its variants for `formatStr`
9// it will format dates in whichever way is appropriate to the locale
10export const format = (date: DateType, formatStr = "PP") => {
11 const locale =
12 typeof window !== "undefined"
13 ? locales[window.__localeId__]
14 : locales[global.__localeId__]; // Check browser, server
15
16 return fnsFormat(date, formatStr, {
17 locale,
18 });
19};

2. Setup server side

App currently does not support Next.js Data Fetching methods like getStaticProps or getServerSideProps.

_app.tsx

1MyApp.getInitialProps = async (appContext: AppContext) => {
2 const { router } = appContext;
3 const locale = router.locale; // 'ko' or 'en'
4 const appProps = await App.getInitialProps(appContext);
5
6 global.__localeId__ = locale;
7
8 return { ...appProps };
9};

3. Setup client side

_document.tsx

1loadWindowProperty = (locale) => (
2 <script
3 dangerouslySetInnerHTML={{
4 __html: `window.__localeId__ = "${locale}"`,
5 }}
6 ></script>
7);
8
9render() {
10 const { loadWindowProperty } = this;
11 const { locale } = this.props; // 'ko' or 'en'
12
13 return (
14 <Html>
15 <body>
16 {loadWindowProperty(locale)}

4. Use custom format function

1import { format } from "src/libs/date";
2
3format(Date.now(), "MMM d',' Y");

참고