1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

Supabase Authでセッションからログイン認可をしようとしたところなぜかできくなくなったのでまとめておきます

問題

以下のコードで認証するページをつくったところ何故か認証されませんでした

import Link from "next/link";
import { createClient } from "@/utils/supabase/client";

export default async function Page() {
  const { data, error } = await createClient().auth.getUser();
  if (error || !data?.user) {
    console.error("認証セッションが不正です");
    return { redirectToLogin: true };
  }
  return (
    <>
      <h1>Admin Page</h1>
      <Link href={"/admin/curriculum"}>カリキュラム</Link>
    </>
  );
}

他のページは認可できているので何かがおかしい

解決方法

createClientがクライアント用を利用していました

import { createClient } from "@/utils/supabase/client";

クライアント用ではセッションなどを取る処理が入っていないのでそれは認証認可できっこありません

client.ts
export function createClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );
}

ということで以下に変更したことで治りました

import { createClient } from "@/utils/supabase/server";

ちゃんとこちらは認証の処理があるのでうまくいきます

server.ts
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";

export function createClient() {
  const cookieStore = cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value, ...options });
          } catch (error) {
            // The `set` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
        remove(name: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value: "", ...options });
          } catch (error) {
            // The `delete` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
      },
    }
  );
}

おわりに

思ったよりも検証に時間がかかりましたが解決できてよかったです
前にも別の問題で認証につまづいたので少し難しいと思いました

参考

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?