0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nextjsをvercelに上げたらでたエラーその3: is possibly 'undefined'

Posted at

この記事ではNextjsでvercelに上げたらでたエラーについて書いています。

エラーコード

./src/app/account/page.tsx:39:14
Type error: 'session.user' is possibly 'undefined'.
  37 |           <h1 className="text-3xl font-bold mb-4">
  38 |             {/* {session.user.name}さんのアカウント */}
> 39 |             {session.user.name}&apos;さんのアカウント
     |              ^
  40 |           </h1>
  41 |           <p>メールアドレス: {session.user.email}</p>
  42 |           <button
Static worker exited with code: 1 and signal: null
Error: Command "npm run build" exited with 1

エラー内容

このエラーは、TypeScriptがsession.userがundefinedの可能性があるため
session.user.nameにアクセスする際に型エラーが発生していることを示しています。

useSession()から取得されるsessionオブジェクトは、認証されていない場合には
undefinedになる可能性があるため、このエラーが発生しています。

エラー解決方法

sessionオブジェクトがundefinedでないことを確認してから
session.userにアクセスするようにします。
sessionが存在しない場合に備えて条件分岐を追加しました。

if (status === "authenticated" && session?.user) {
  return (
    <div>
      <div>
        <h1>
          {session.user.name}&apos;さんのアカウント
        </h1>
        <p>メールアドレス: {session.user.email}</p>
        <button onClick={handleSignOut}>
          サインアウト
        </button>
      </div>
    </div>
  );
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?