LoginSignup
31
25

More than 3 years have passed since last update.

Next.js SSRのセッション管理

Posted at

はじめに

SSR(Server Side Rendering)の場合はセッションを使ってユーザー認証管理は一般的です。
Next.jsもいくつかのセッション管理ツールがありますので、少しまとめてみます。

next-authとは

The NextAuth library uses Express and Passport, the most commonly used authentication library for Node.js, to provide support for signing in with email and with services like Facebook, Google and Twitter.
NextAuth adds Cross Site Request Forgery (CSRF) tokens and HTTP Only cookies, supports universal rendering and does not require client side JavaScript.

next-auth: https://github.com/iaincollins/next-auth

インストール

npm install next-auth

クライアント使うサンプル

import React from 'react'
import { NextAuth } from 'next-auth/client'

export default class extends React.Component {
  static async getInitialProps({req}) {
    return {
      session: await NextAuth.init({req})
    }
  }
  render() {
    if (this.props.session.user) {
      return(
        <div>
          <p>ログイン中です。</p>
        </div>
        )
    } else {
      return(
        <div>
          <p>未ログインです。</p>
        </div>
      )
    }
  }
}

サーバ側

./pages/authフォルダーにページ作成

  • index.js NextAuth.signinメソッドを実行し、ログイン成功、失敗を判断
  • error.js 認証失敗の処理

重要な3つの設定ファイル

参考:https://github.com/iaincollins/next-auth
サンプル:https://github.com/iaincollins/next-auth/blob/master/example/pages/auth/index.js

passport

passport:http://www.passportjs.org/

cookie

サンプル:https://github.com/zeit/next.js/tree/canary/examples/with-cookie-auth

firebase

サンプル:https://github.com/zeit/next.js/tree/canary/examples/with-firebase-authentication

以上

31
25
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
31
25