を使用します.同じnextjsアプリのJS


これは私の最初のチュートリアルです、この1つの意図は、生命を簡単にし、同じプロジェクトでこれらの技術を実装する必要がある人のための時間を節約することです、私はそれを実装するために私にしばらくかかったと私はそれを必要とする可能性があります誰とでも共有したい.
閉じるこの動画はお気に入りから削除されています.

1. We create a new project as indicated in the documentation .


私はタイプスクリプトでそれをするつもりです、しかし、Javascriptで、ステップは同じです.
npx create-next-app@latest --typescript
プロジェクトの名前を入力し、依存関係をインストールするのを待ち、プロジェクトフォルダでコードエディターまたはコードエディターを実行します.
これで端末タイプです.
npm run dev
これはポート3000の開発サーバを起動します.

Next - I 18 NEXTのインストールと設定


プロジェクトリポジトリに表示されるように
yarn add next-i18next 
# Si usas NPM ejecuta:
npm i --save next-i18next
ここでは、JSONファイルを使って2つのフォルダを作成して翻訳をテストします.
└─ public
   └ locales
     ├─en
     | └─ common.json
     └─es
       └─ common.json
それから、我々はnext-i18next.config.js 次のコンテンツを含むプロジェクトのルートファイルです.
module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'es'],
  },
};
それからnext.config.js ファイルを設定します
/** @type {import('next').NextConfig} */
const { i18n } = require("./next-i18next.config");
const nextConfig = {
  reactStrictMode: true,
  i18n,
};

module.exports = nextConfig;
最後に我々はpages/_app.tsx 翻訳を使用してアプリケーションを実行するファイルは、最後の行で変更されます.
import '../styles/globals.css';
import type { AppProps } from 'next/app';
import { appWithTranslation } from 'next-i18next';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default appWithTranslation(MyApp);

追加とテストの翻訳。


ファイルにpublic/locales/en/common.json and public/locales/en/common.json この方法で翻訳を追加します.public/locales/en/common.json
{
  "welcome": "Welcome to the world of Next.js!",
  "content": "This is the blog index page"
}
public/locales/en/common.json
{
  "welcome": "Bienvenido al mundo de Next.js!",
  "content": "Esta es la página de inicio del blog"
}
さて、このステップは重要です、翻訳が正しく働くために、彼らは正確に「水和」を実行するためにページレベルですべての構成要素のサーバーから呼ばれなければなりませんpages/index.tsx 翻訳をパスするファイルなので、それぞれの翻訳を個別に呼び出すことができます
const { t } = useTranslation('common');
この場合のファイルは次のようになります.
import type { NextPage, NextPageContext } from 'next';
import Head from 'next/head';
import Image from 'next/image';
import styles from '../styles/Home.module.css';

const Home: NextPage = () => {
  const { t } = useTranslation('common');
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>{t('welcome')}</h1>

        <p className={styles.description}>{t('content')}</p>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  );
};

export default Home;
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';

export async function getStaticProps({ locale }: NextPageContext) {
  return {
    props: {
      ...(await serverSideTranslations(locale || 'en', ['common'])),
    },
  };
}
結果は、システムで検出された言語を使用した翻訳ページです.

もし私たちが手動で言語変更をテストしたいならば、私たちは設定を変えなければなりません、また、私は我々のプロジェクトをアップロードするのに役立つもう一つの線を加えますVercel , ファイルは次のようになります.
const path = require('path');

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'es'],
    localeDetection: false,
    localePath: path.resolve('./public/locales'), // for deployment on Vercel
  },
};
また、手動で言語を変更するボタンを作成しますpages/index.tsx ファイルは以下のようになります:
import type { NextPage, NextPageContext } from 'next';
import Head from 'next/head';
import Image from 'next/image';
import styles from '../styles/Home.module.css';
import { useRouter } from 'next/router';

const Home: NextPage = () => {
  const router = useRouter();
  const { pathname, asPath, query } = router;
  const { t } = useTranslation('common');
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>{t('welcome')}</h1>

        {/* Language Change Button */}
        <button
          type="button"
          onClick={() => {
            router.push({ pathname, query }, asPath, {
              locale: router.locale === 'es' ? 'en' : 'es',
            });
          }}
        >
          {router.locale === 'es' ? 'English' : 'Español'}
        </button>

        <p className={styles.description}>{t('content')}</p>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  );
};

export default Home;
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';

export async function getStaticProps({ locale }: NextPageContext) {
  return {
    props: {
      ...(await serverSideTranslations(locale || 'en', ['common'])),
    },
  };
}
このように我々はすでにルートに基づいて2つの言語で完全に取り組んで我々のアプリケーションを持っている

次の認証で認証を設定します


まずパッケージをインストールします.
npm i --save next-auth
テストの目的のために我々は資格情報(電子メールとパスワード)を使用します、また、我々はそれが正しくあなたのプロジェクトで必要なものに依存して、単純な検証を行います場合は、コメントをする場合は、異なるプロバイダとの認証を行う方法を説明するチュートリアルを行うことができますカスタマイズ可能なホームページを使用します.それは、我々が続くと言いました.
私たちはpages/api/auth/[...nextauth].ts ファイル.
次のコンテンツを使用します.
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: {
          label: 'Email',
          type: 'email',
          placeholder: '[email protected]',
        },
        password: {
          label: 'Password',
          type: 'password',
          placeholder: '********',
        },
      },
      async authorize(credentials) {
        if (credentials && credentials.email && credentials.password) {
          if (
            credentials.email === '[email protected]' &&
            credentials.password === 'test'
          ) {
            return {
              email: credentials.email,
              image: 'https://i.pravatar.cc/500',
              name: 'Test User',
            };
          }
        }
        return null;
      },
    }),
  ],
  callbacks: {
    jwt: async ({ token }) => {
      return token;
    },
    session: ({ session, token }) => {
      if (token) {
        session.id = token.id;
      }
      return session;
    },
  },
  secret: 'my-secret',
  jwt: {
    secret: 'my-secret',
    maxAge: 60 * 60 * 24 * 30,
  },
});
その後、我々はpages/index.tsx ファイルは、言語の変更に加えて、認証またはログアウトボタンを持っている.
import type { NextPage, NextPageContext } from 'next';
import Head from 'next/head';
import Image from 'next/image';
import styles from '../styles/Home.module.css';
import { useRouter } from 'next/router';
import { useSession, signIn, signOut } from 'next-auth/react';

const Home: NextPage = () => {
  const router = useRouter();
  const { pathname, asPath, query } = router;
  const { t } = useTranslation('common');
  const { data: session } = useSession();

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>{t('welcome')}</h1>

        {/* Language Change Button */}
        <button
          type="button"
          onClick={() => {
            router.push({ pathname, query }, asPath, {
              locale: router.locale === 'es' ? 'en' : 'es',
            });
          }}
        >
          {router.locale === 'es' ? 'English' : 'Español'}
        </button>

        {/* Authentication Button */}
        {session ? (
          <>
            <h4>
              {t('welcome')} {JSON.stringify(session.user)}
            </h4>
            <button
              type="button"
              onClick={() => {
                signOut();
              }}
            >
              {t('signOut')}
            </button>
          </>
        ) : (
          <button
            type="button"
            onClick={() => {
              signIn();
            }}
          >
            {t('signIn')}
          </button>
        )}

        <p className={styles.description}>{t('content')}</p>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  );
};

export default Home;
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';

export async function getStaticProps({ locale }: NextPageContext) {
  return {
    props: {
      ...(await serverSideTranslations(locale || 'en', ['common'])),
    },
  };
}
今、最も重要なことは、おそらく、あなたがこのポストに来て、なぜ個人的に私は、解決するために最も困難を発見した理由は、ちょうど小さな変化をpages/_app.tsx SessionProviderが翻訳プロバイダーと衝突しないようにするファイルです.
import '../styles/globals.css';
import type { AppProps } from 'next/app';
import { appWithTranslation } from 'next-i18next';
import { SessionProvider } from 'next-auth/react';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

const AppWithI18n = appWithTranslation(MyApp);

const AppWithAuth = (props: AppProps) => (
  <SessionProvider session={props.pageProps.session}>
    <AppWithI18n {...props} />
  </SessionProvider>
);

export default AppWithAuth;
そして、それは今、我々は我々のページの言語を変更することができますし、同じnextjsアプリケーションで認証を持っている.


あなたがコメントや質問を持っているならば、私はあなたを助けたことを望みます.