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?

More than 1 year has passed since last update.

@supabase/auth-helpersのcreateRouteHandlerSupabaseClientでログイン後にセッションが取得できない

Posted at

遭遇した問題

API Handlerを使い、以下のようなコードでログイン処理を実装しました。
その際@supabase/auth-helpersのcreateRouteHandlerSupabaseClientを使用しました。

lib/supabase/server.ts
import { createRouteHandlerSupabaseClient } from "@supabase/auth-helpers-nextjs";
import { headers, cookies } from "next/headers";

export const createClientRouteHandler = () =>
  createRouteHandlerSupabaseClient({
    supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL!,
    headers,
    cookies,
  });
app/api/auth/login/route.ts
import { NextResponse } from "next/server";
import { createClientRouteHandler } from "~/lib/supabase/server";

export async function POST(request: Request) {
  const supabase = createClientRouteHandler();
  const user = await supabase.auth.signInWithPassword({
    email: res.email,
    password: res.password,
  });
  ...

しかし、他のファイルで以下のようなコードでセッションを取得しようとしてもnullが返ってきます。

import { NextResponse } from "next/server";
import { createClientRouteHandler } from "~/lib/supabase/server";

export async function GET(request: Request) {
  const supabase = createClientRouteHandler();
  const { error, data } = await supabase.auth.getUser();
  console.log(data); // { user: null }

原因

Supabase公式の以下のYoutube動画で指摘されているようにNext.js側のバグの可能性が高く、cookieがうまく渡ってきていないことに起因すると思われます。
https://www.youtube.com/watch?v=KmJN-bEayeY&t=600s

対処法

Next.js側が対応するのを待つしかなさそうなので、一旦こういった処理はServer ComponentやClient Component側に移すことにしました。

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?