Open7

Next.js 14の勉強

twktwk

Next.js素人なので大間違いの可能性あり。

twktwk

Auth.jsならwithAuth、nextjs-auth0ならwithMiddlewareAuthRequiredを使って下記のようにmiddlewareを書けば良い模様。

import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
import { NextFetchEvent, NextRequest } from 'next/server';
import createIntlMiddleware from 'next-intl/middleware';

// https://next-intl-docs.vercel.app/docs/routing/middleware#example-auth-js
const intlMiddleware = createIntlMiddleware({
  locales: ['en', 'ja'],
  defaultLocale: 'en',
  localePrefix: 'never' // no redirect to the locale sub folder
});

const authMiddleware = withMiddlewareAuthRequired(
  (req) => intlMiddleware(req)
);

export default function middleware(req: NextRequest, event: NextFetchEvent) {
  // Currently all pages are treated as public pages. The dashboard is protected with UserProvider in the layout file
  const publicPathnameRegex = RegExp(
    `/((?!api|_next|.*\\..*).*)`, 
    'i'
  );
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname);
  
  if (isPublicPage) {
    return intlMiddleware(req);
  } else {
    return authMiddleware(req, event);
  }
}

// all pages except api or static files
export const config = {
   matcher: ['/((?!api|_next|.*\\..*).*)']
};
twktwk

通常のサーバーコンポーネントのPageでは

import {useTranslations} from 'next-intl';
const t = useTranslations('Index');

<Suspense />タグを使っているなどawaitが発生するようなところでは

import {getTranslations} from 'next-intl/server';
const t = await getTranslations('Index');