4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsとSupabase AuthでgetUserがnullになる

Last updated at Posted at 2024-06-02

はじめに

Next.jsでsupabaseのAuthを使っている中で沼った箇所を書いていきます

問題

ドキュメント通りに設定をして、アプリケーション開発を行っていたところとあるタイミングで以下の認可のコードでユーザーが取得できなくなりました


  const { data, error } = await supabase.auth.getUser();
  if (error || !data?.user) {
    redirect("/login");
  }

さっきまでユーザーが取れていたのにとナゾになっていました

解決方法

middleware.tsのimportがNextResponseよりも手前になっていたのが原因でした

これは動かない

import { updateSession } from "@/utils/supabase/middleware";
import { type NextRequest } from "next/server";

これならうごく

import { type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";

最初に検証のときにはうまく設定しており、次にアプリケーション設定をしたときにミスをしていました
最初成功していたのでセッションがずっと効いていたようでログアウトをしたあとから、middleware.tsの位置がおかしいのでセッションをセットすることができなくなっていました

おわりに

突然起きてしまい数時間を使ってしまいましたがmiddlewareについて理解をふかめられましt

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?