LoginSignup
3
1

More than 3 years have passed since last update.

Next.js × Auth0でログイン機能を追加する。

Last updated at Posted at 2021-05-14

はじめに

Next.js×Auth0を使ってログイン機能を作成します。

公式のページが一番分かりやすく、簡単だったのでそちらの方法で進めていきます。

必要なもの

1.Auth0のアカウント
2.npm install @auth0/nextjs-auth0

1.アカウントを作成する。

アカウントを作成したらDashboardからApplications
スクリーンショット 2021-05-13 8.37.12.png

アプリケーションを作成

スクリーンショット 2021-05-13 8.38.00.png

名前を決めて、SPAを選択

ダッシュボードページに移行したら
Setting

スクリーンショット 2021-05-13 8.49.19.png

Allowed Callback URLhttp://localhost:3000/api/auth/callback
Logout URLhttp://localhost:3000
と設定します。

QuickStartページに移行し、Next.jsと入力します。
スクリーンショット 2021-05-13 8.44.06.png
スクリーンショット 2021-05-13 8.45.34.png

2.Next.js

authインストール

auth0をインストールします。
npm install @auth0/nextjs-auth0

keyを取得

ルートディレクトリの中に.env.localファイルを作成し、以下の内容をコピペします。
スクリーンショット 2021-05-13 8.55.31.png

page/apiの中にauth/[...auth0].jsを作成

[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

UseProviderを設定

`pages/_app.jsxにuseProviderをimportします。

_app.jsx
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

Loginボタン,Logoutボタンを作成

<a href="/api/auth/login">Login</a>
<a href="/api/auth/logout">Logout</a>

クリックするとログインページに移動します。
スクリーンショット 2021-05-14 17.33.18.png

参考にしたページ

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1