英文:
Error using Next.js13 and Next/Supabase auth
问题
以下是您要翻译的内容:
一旦我登录,就会出现这个问题:
无法解析Cookie字符串:[错误:Edge运行时不支持Node.js的'buffer'模块。
了解更多信息:https://nextjs.org/docs/messages/node-module-in-edge-runtime]。
middleware.ts:
import { createMiddlewareSupabaseClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import { Database } from "./types/supabase";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const pathname = req.nextUrl.pathname;
const supabase = createMiddlewareSupabaseClient<Database>({ req, res });
const {
data: { session },
} = await supabase.auth.getSession();
if (!session && pathname === "/") {
const url = new URL(req.url);
url.pathname = "/login";
return NextResponse.redirect(url);
}
return res;
}
supabase-auth-provider:
"use client";
import { Profile } from "../../types/collections";
import { Session } from "@supabase/supabase-js";
import { useRouter } from "next/navigation";
import { createContext, useContext, useEffect } from "react";
import useSWR from "swr";
import { useSupabase } from "./supabase-provider";
interface ContextI {
user: Profile | null | undefined;
error: any;
isLoading: boolean;
mutate: any;
signOut: () => Promise<void>;
signInWithGithub: () => Promise<void>;
signInWithEmail: (email: string, password: string) => Promise<string | null>;
}
const Context = createContext<ContextI>({
user: null,
error: null,
isLoading: true,
mutate: null,
signOut: async () => {},
signInWithGithub: async () => {},
signInWithEmail: async (email: string, password: string) => null,
});
export default function SupabaseAuthProvider({
serverSession,
children,
}: {
serverSession?: Session | null;
children: React.ReactNode;
}) {
const { supabase } = useSupabase();
const router = useRouter();
// 获取用户
const getUser = async () => {
const { data: user, error } = await supabase
.from("profiles")
.select("*")
.eq("id", serverSession?.user?.id)
.single();
if (error) {
console.log(error);
return null;
} else {
return user;
}
};
const {
data: user,
error,
isLoading,
mutate,
} = useSWR(serverSession ? "profile-context" : null, getUser);
// 注销
const signOut = async () => {
await supabase.auth.signOut();
router.push("/login");
};
// 使用Github登录
const signInWithGithub = async () => {
await supabase.auth.signInWithOAuth({ provider: "github" });
};
// 使用电子邮件登录
const signInWithEmail = async (email: string, password: string) => {
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return error.message;
}
return null;
};
// 刷新页面以同步服务器和客户端
useEffect(() => {
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((event, session) => {
if (session?.access_token !== serverSession?.access_token) {
router.refresh();
}
});
return () => {
subscription.unsubscribe();
};
}, [router, supabase, serverSession?.access_token]);
const exposed: ContextI = {
user,
error,
isLoading,
mutate,
signOut,
signInWithGithub,
signInWithEmail,
};
return <Context.Provider value={exposed}>{children}</Context.Provider>;
}
export const useAuth = () => {
let context = useContext(Context);
if (context === undefined) {
throw new Error("useAuth必须在SupabaseAuthProvider内部使用");
} else {
return context;
}
};
希望这可以帮助您理解您的问题所在。如果需要更多帮助,请随时提问。
英文:
Once I do the login this problem appears :
Failed to parse cookie string: [Error: The edge runtime does not support Node.js 'buffer' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime].
middleware.ts:
import { createMiddlewareSupabaseClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import { Database } from "./types/supabase";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const pathname = req.nextUrl.pathname;
const supabase = createMiddlewareSupabaseClient<Database>({ req, res });
const {
data: { session },
} = await supabase.auth.getSession();
if (!session && pathname === "/") {
const url = new URL(req.url);
url.pathname = "/login";
return NextResponse.redirect(url);
}
return res;
}
supabase-auth-provider:
"use client";
import { Profile } from "../../types/collections";
import { Session } from "@supabase/supabase-js";
import { useRouter } from "next/navigation";
import { createContext, useContext, useEffect } from "react";
import useSWR from "swr";
import { useSupabase } from "./supabase-provider";
interface ContextI {
user: Profile | null | undefined;
error: any;
isLoading: boolean;
mutate: any;
signOut: () => Promise<void>;
signInWithGithub: () => Promise<void>;
signInWithEmail: (email: string, password: string) => Promise<string | null>;
}
const Context = createContext<ContextI>({
user: null,
error: null,
isLoading: true,
mutate: null,
signOut: async () => {},
signInWithGithub: async () => {},
signInWithEmail: async (email: string, password: string) => null,
});
export default function SupabaseAuthProvider({
serverSession,
children,
}: {
serverSession?: Session | null;
children: React.ReactNode;
}) {
const { supabase } = useSupabase();
const router = useRouter();
// Get USER
const getUser = async () => {
const { data: user, error } = await supabase
.from("profiles")
.select("*")
.eq("id", serverSession?.user?.id)
.single();
if (error) {
console.log(error);
return null;
} else {
return user;
}
};
const {
data: user,
error,
isLoading,
mutate,
} = useSWR(serverSession ? "profile-context" : null, getUser);
// Sign Out
const signOut = async () => {
await supabase.auth.signOut();
router.push("/login");
};
// Sign-In with Github
const signInWithGithub = async () => {
await supabase.auth.signInWithOAuth({ provider: "github" });
};
// Sign-In with Email
const signInWithEmail = async (email: string, password: string) => {
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return error.message;
}
return null;
};
// Refresh the Page to Sync Server and Client
useEffect(() => {
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((event, session) => {
if (session?.access_token !== serverSession?.access_token) {
router.refresh();
}
});
return () => {
subscription.unsubscribe();
};
}, [router, supabase, serverSession?.access_token]);
const exposed: ContextI = {
user,
error,
isLoading,
mutate,
signOut,
signInWithGithub,
signInWithEmail,
};
return <Context.Provider value={exposed}>{children}</Context.Provider>;
}
export const useAuth = () => {
let context = useContext(Context);
if (context === undefined) {
throw new Error("useAuth must be used inside SupabaseAuthProvider");
} else {
return context;
}
};
I've tried checking what the problem is but there´s nothing about it anywhere.
答案1
得分: 2
我在将middleware.js文件放在应用程序目录之外时遇到了这个问题,也许这就是你遇到的问题。
英文:
I had that problem when I put the middleware.js file outside the app directory, maybe that's the problem you have.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论