next-auth middleware stuck on login page
Answered
Giant panda posted this in #help-forum
Giant pandaOP
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized({ req, token }) {
if (req.nextUrl.pathname.startsWith("/dashboard") && token === null) {
return false;
}
return true;
},
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)", "/dashboard"],
};299 Replies
Giant pandaOP
The middleware is not allowing access to the protected routes even though I'm authenticated
are you able to try it on different browser?
Giant pandaOP
yes tried on both firefox and chromium(night-build)
but it didn't work
Giant pandaOP
const Home = () => {
const { status } = useSession();
const isAuth = status === "authenticated";
const path = isAuth ? "/dashboard" : "/api/auth/signIn";
return (
<section className="relative">
<div className="relative z-10 max-w-screen-xl mx-auto px-4 py-28 md:px-8">
<div className="space-y-5 max-w-4xl mx-auto text-center">
<h2 className="text-4xl text-gray-800 dark:text-white font-extrabold mx-auto md:text-5xl">
Snippy: Effortlessly Beautify Your Code Snippets in Seconds!
</h2>
<p className="max-w-2xl mx-auto text-gray-600 dark:text-gray-200">
Create, Customize, and Share Stunning Code Snippets with Snippy
</p>
<div className="flex justify-center items-center gap-x-2 sm:flex">
<Link
as="/dashboard"
href={path}
prefetch={false}
className="flex items-center justify-center gap-x-2 py-2.5 px-4 mt-3 w-full text-sm text-white font-medium bg-purple-500 hover:bg-purple-400 active:bg-purple-600 duration-150 rounded-lg sm:mt-0 sm:w-auto"
>
Get started
<RightArrow />
</Link>
</div>
<div className="max-w-xl hidden md:block w-full mx-auto border-none outline-none bg-background"></div>
</div>
</div>
<div
className="absolute inset-0 m-auto max-w-xs h-[357px] blur-[118px] sm:max-w-md md:max-w-lg"
style={gradientBackground}
></div>
</section>
);
};
export default Home;Giant pandaOP
no
😞
import { getServerSession, Session } from "next-auth";
import type { NextAuthOptions } from "next-auth";
import Github from "next-auth/providers/github";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "./prisma";
import {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from "next";
export const authOptions = {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token, user }) {
session.user.id = user.id;
return session;
},
async redirect({ url, baseUrl }) {
return baseUrl;
},
},
} satisfies NextAuthOptions;
export function auth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, authOptions);
}is there any way to use getServerSession in middleware ?
@Giant panda is there any way to use getServerSession in middleware ?
I dont think so, why you need it in middleware?
Giant pandaOP
because next-auth middleware is not working properly

i test your code and it work on my side
can you share it on github?
Giant pandaOP
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized: ({ req }) => {
const { pathname } = req.nextUrl;
// smh I managed to fix it
return (
pathname !== "/dashboard" &&
Boolean(req.cookies.get("next-auth.session-token"))
);
},
},
pages: {
error: "/auth/error",
signIn: "/api/auth/signin",
},
});
export const config = {
matcher: ["/dashboard", "/((?!_next/static|favicon.ico|login|).*)"],
};@Ray i test your code and it work on my side
Giant pandaOP
can you share your code
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized({ req, token }) {
if (req.nextUrl.pathname.startsWith("/dashboard") && token === null) {
return false;
}
return true;
},
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)", "/dashboard"],
};import Image from "next/image";
import { Inter } from "next/font/google";
import Link from "next/link";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
return (
<main
className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`}
>
<Link href="/dashboard" prefetch={false}>
start
</Link>
</main>
);
}export default function Dashboard() {
return <h1>Dashboard</h1>;
}Giant pandaOP
wait so when I restart the server then again it is throwing same error
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized: ({ req }) => {
const { pathname } = req.nextUrl;
// smh I managed to fix it
return (
pathname !== "/dashboard" &&
Boolean(req.cookies.get("next-auth.session-token"))
);
},
},
pages: {
error: "/auth/error",
signIn: "/api/auth/signin",
},
});
export const config = {
matcher: ["/dashboard", "/((?!_next/static|favicon.ico|login|).*)"],
};"next": "14.0.4",
"next-auth": "^4.24.5",Giant pandaOP
"next": "14.0.4",
"next-auth": "^4.24.5",
"next-auth": "^4.24.5",
😑
@Ray ts
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized({ req, token }) {
if (req.nextUrl.pathname.startsWith("/dashboard") && token === null) {
return false;
}
return true;
},
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)", "/dashboard"],
};
Giant pandaOP
can you share your next-auth config
😞
import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions = {
providers: [
CredentialsProvider({
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
authorize(credentials, req) {
const user = { id: "1", name: "J Smith", email: "jsmith@example.com" };
if (user) {
return user;
} else {
return null;
}
},
}),
],
} satisfies NextAuthOptions;
export default NextAuth(authOptions);Giant pandaOP
import { getServerSession, Session } from "next-auth";
import type { NextAuthOptions } from "next-auth";
import Github from "next-auth/providers/github";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "./prisma";
import {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from "next";
export const authOptions = {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token, user }) {
session.user.id = user.id;
return session;
},
async redirect({ url, baseUrl }) {
return baseUrl;
},
},
} satisfies NextAuthOptions;
export function auth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, authOptions);
}anything wrong in this ?
try remove
async redirect({ url, baseUrl }) {
return baseUrl;
},Giant pandaOP
ok
Giant pandaOP
authentication is working fine without middleware

https://github.com/nextauthjs/next-auth/issues/5170 wait so I'm getting null token in middleware
not sure why you getting __client_uat cookies error
does it work if you remove the callback in middleware
I think only the matcher is needed
Giant pandaOP
User
NEXTAUTH_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
# This was inserted by `prisma init`:
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL=
NEXTAUTH_URL=http://localhost:3000
NEXT_PUBLIC_APP_URL=http://localhost:3000 env filewait do we need different secret variables for middleware and next-auth ?
no
https://github.com/vvo/iron-session
try this maybe lol
try this maybe lol
I don't know if it's the app router causing this shit issue or if it's NextAuth
well or try next-auth@beta
Giant pandaOP
I'm thinking to go with clerk or auth0
@Giant panda I don't know if it's the app router causing this shit issue or if it's NextAuth
your code work with app router for me too
Giant pandaOP
but you didn't use github provider in next-auth config
Giant pandaOP
oh can you share you code files
😞
import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GithubProvider from "next-auth/providers/github";
export const authOptions = {
secret: process.env.NEXTAUTH_SECRET,
providers: [
GithubProvider({
clientId: `${process.env.GITHUB_CLIENT_ID}`,
clientSecret: `${process.env.GITHUB_CLIENT_SECRET}`,
}),
CredentialsProvider({
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
authorize(credentials, req) {
const user = { id: "1", name: "J Smith", email: "jsmith@example.com" };
if (user) {
return user;
} else {
return null;
}
},
}),
],
} satisfies NextAuthOptions;
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };Giant pandaOP
thanks
@Ray do you have these setting on github?
Giant pandaOP
wait that callback url seems wrong to me
Giant pandaOP
is this your middleware
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized({ req, token }) {
if (req.nextUrl.pathname.startsWith("/dashboard") && token === null) {
return false;
}
return true;
},
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)", "/dashboard"],
};Giant pandaOP
import { Toaster } from "@/components/ui/sonner";
import { ThemeProvider } from "@/components/theme-provider";
import AuthProvider from "@/components/auth-provider";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
return (
<AuthProvider session={session}>
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
<Toaster />
</ThemeProvider>
</body>
</html>
</AuthProvider>
);
}Giant pandaOP
still same issue "http://localhost:3000/api/auth/signin?callbackUrl=%2F" it is not redirecting to correct url
@Giant panda still same issue "http://localhost:3000/api/auth/signin?callbackUrl=%2F" it is not redirecting to correct url
did you remove the
redirect function in auth configGiant pandaOP
yes
@Giant panda still same issue "http://localhost:3000/api/auth/signin?callbackUrl=%2F" it is not redirecting to correct url
what url are you expecting it to redirect to?
Giant pandaOP
like if the request is for dashboard then it should redirect to the dashboard after signin process
Shouldn't it handle redirection on its own?
or do I need to handle it manually
it should redirect to the callbackUrl
did it redirect you to
/?Giant pandaOP
export { default } from "next-auth/middleware";
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)", "/dashboard"],
}; no it is stuck on signin pageimport { getServerSession, Session } from "next-auth";
import type { NextAuthOptions } from "next-auth";
import Github from "next-auth/providers/github";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "./prisma";
import {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from "next";
export const authOptions = {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.NEXTAUTH_SECRET!,
callbacks: {
async session({ session, token, user }) {
session.user.id = user.id;
return session;
},
},
} satisfies NextAuthOptions;
export function auth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, authOptions);
}Giant pandaOP
yeah
cookies are working fine
well let me push my code to github and you test it on your device
Giant pandaOP

Giant pandaOP

let me know if it works on your side
Giant pandaOP
import AuthProvider from "@/components/auth-provider";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<AuthProvider>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
<Toaster />
</ThemeProvider>
</AuthProvider>
</body>
</html>
);
} do i need to pass the session in auth provider ?Giant pandaOP
so I copied everything like you did in your setup
but still this shit popping up
wait what is your callback url for github
?
Giant pandaOP
nothing changed lol
@Giant panda Click to see attachment
are you using github app or oauth apps?
im using oauth apps
because your cookies coming from github look different than mine
Giant pandaOP
oauth apps
well I have no idea what happen on your side lol
@Giant panda Click to see attachment
look like the cookies failed to set
Giant pandaOP
yes it cannot set the cookie from github
Giant pandaOP
in your side too ?
no
@Ray Click to see attachment
you can see bunch of cookie from github
Giant pandaOP
even tried running on librewolf bruh
do you have some thing preventing the cookie being set
Giant pandaOP
I've already running the app on multiple browsers
create a new oauth app?
Giant pandaOP
k
Giant pandaOP
does it work with other provider
Giant pandaOP
let me test
Giant pandaOP
okay, so authentication works fine without middleware; otherwise, it gets stuck on the sign-in page.
ah
have you tried v5?
Giant pandaOP
fk this shit I'm done
Giant pandaOP
but this shit never happened before
😞
and next-auth doesn't support database session with credential
this is the main reason I don't use it anymore
Giant pandaOP
If you're trying to use NextAuth v5 in Routes with Adapter that prevents middleware usage lolyou were using v5?
Giant pandaOP
no but error is kinda same
well but it work on my side lol
maybe I dont use adapter
Giant pandaOP
what's your node vesion
v20.7.0
Giant pandaOP
I'm so confused rn
so I removed the adapter, it is working fine smh
Giant pandaOP
Giant pandaOP
Answer
let me try with prisma adaptor
Giant pandaOP
Do you have clones or something? It seems like you're everywhere, lol
well i have a project for helping ppl on discord, I just install whatever when i need lol
Giant pandaOP

yes seem it break it
Giant pandaOP
f
lucia or iron-session ðŸ‘ðŸ¾
Giant pandaOP
which supports oauth ?
lucia
Giant pandaOP
so I think I should close this thread
Giant pandaOP
solution would be "stop using next-auth"
yea that's what ive already done

Giant pandaOP
😄
btw thanks a lot for the help!
so I found this on their github issues
lets come back when they are fully support edge 

Giant pandaOP
ok 😢
I'm closing this thread
ok
Giant pandaOP
wait
I forgot how to close it damn my brain ain't workin
right click an answer > application > mark solution
Giant pandaOP
I can't find it srry
😵
which one should be the answer
@Ray 😵
Giant pandaOP
this -> "Don't use an adapter with next-auth."
lol
Giant pandaOP
dude lucia-auth is ass long to setup lol
yea it gives you control on everything
Giant pandaOP
at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/esm/server/future/route-modules/app-route/module.js:218:37)
[auth][details]: {}
[auth][error] AdapterError: Read more at https://errors.authjs.dev#adaptererror
[auth][cause]: Error: PrismaClient is unable to run in Vercel Edge Functions. As an alternative, try Accelerate: https://pris.ly/d/accelerate.I think this is nextjs problem
Giant pandaOP
prisma won't work in middleware
are you trying to use prisma in middelware?
Giant pandaOP
import { PrismaClient } from "@prisma/client/edge";
import { withAccelerate } from "@prisma/extension-accelerate";
const prismaClientSingleton = () => {
return new PrismaClient().$extends(withAccelerate());
};
declare global {
var prisma: undefined | ReturnType<typeof prismaClientSingleton>;
}
const prisma = globalThis.prisma ?? prismaClientSingleton();
export default prisma;
if (process.env.NODE_ENV !== "production") globalThis.prisma = prisma;import GitHub from "next-auth/providers/github";
import type { NextAuthConfig } from "next-auth";
export const authConfig = {
providers: [
GitHub({
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
}),
],
} satisfies NextAuthConfig;import { authConfig } from "./auth.config";
import { PrismaAdapter } from "@auth/prisma-adapter";
import NextAuth from "next-auth";
import prisma from "../prisma";
import type { Adapter } from "@auth/core/adapters";
export const {
handlers: { GET, POST },
auth,
} = NextAuth({
adapter: PrismaAdapter(prisma as any) as Adapter,
session: { strategy: "jwt" },
...authConfig,
});Giant pandaOP
ok this shit is fking trash
so I've tried literally everything
@Ray https://github.com/vercel/next-learn/blob/main/dashboard/final-example/middleware.ts
this show how to use middleware with node api
Giant pandaOP
this is using server actions which I don't
want
no
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};@Giant panda this is using server actions which I don't
wait are you using v5 or what
Giant pandaOP
now v5
beta
it separate the prisma code from the authConfig
and made it can be run on edge
Giant pandaOP
ok
@Giant panda ok
can you get it working?

Giant pandaOP
no it didn't work
lol
the file with auth option, only contain callback, pages and leave providers as
[]other option should be set in the main file
Giant pandaOP
I nuked whole file (testing project)
in middleware
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;Giant pandaOP
lets start from scratch lol
lol
how many days have you been playing with next-auth
Giant pandaOP
in main project I'm still using stable release
ah ok
@Ray how many days have you been playing with next-auth
Giant pandaOP
2-3 days
but v5 seem to work better with app router
Giant pandaOP
I think there is some problem with prisma accelerate
it still has some issues with edge
prisma cannot be run in middleware anyway
or it does now?
Giant pandaOP
no I think accelerate was made to fix that
I'm not sure tho
oh something like prisma data proxy before?
oh yea they changed the name
Giant pandaOP
I think it is related to nextjs like user don't have much control over the edge stuff
because he has prisma in
auth.config.ts@Ray https://github.com/vercel/next-learn/blob/main/dashboard/final-example/middleware.ts
this course show how to avoid doing it
Giant pandaOP
ok let's try this
any prisma related should be inside
auth.tsor node api
Giant pandaOP
srry I was checking the wrong repo
@Ray https://github.com/riccardolinares/next-auth-v5/blob/53debe06e833e657f1c303f2b6192c9330b3498d/auth.config.ts#L40
Giant pandaOP
btw , In this it is using middleware outside of the "src" directory
oh
Giant pandaOP
so I think it worked

Giant pandaOP
why is it directing to the dashboard page after signin
@Giant panda Click to see attachment
you could set it redirect to other path in
authorized callbacksGiant pandaOP
// import Stripe from "stripe";
import Github from "next-auth/providers/github";
import prisma from "@/lib/prisma";
declare module "next-auth" {
// eslint-disable-next-line no-unused-vars
interface Session {
user: {
/** The user's id. */
id: string;
} & DefaultSession["user"];
}
}
import type { NextAuthConfig, DefaultSession } from "next-auth";
export default {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session, user }: { session: any; user: any }) {
session.user.id = user.id;
return session;
},
async redirect({
url,
baseUrl,
}: {
url: any | undefined;
baseUrl: any | undefined;
}) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
pages: {
signIn: "/auth/signin", // overrides the next-auth default signin page https://authjs.dev/guides/basics/pages
verifyRequest: "/auth/verify",
error: "/auth/error",
},
} satisfies NextAuthConfig;btw why do I need to keep vercel postgres in sync by db push lol
@Giant panda btw why do I need to keep vercel postgres in sync by db push lol
what do you mean in sync?
Giant pandaOP
like It needs "npx prisma db push" command to keep db in sync with prisma otherwise connection get crashed
@Giant panda like It needs "npx prisma db push" command to keep db in sync with prisma otherwise connection get crashed
oh that should be something about accelerate
im not sure, i've never use it
Giant pandaOP
same lol
can you use prisma without it now?
I have'nt used prisma since drizzle came out
Giant pandaOP
no auth is currently using prisma adapter
the prisma adapter need prisma + accelerate?
Giant pandaOP
import { PrismaClient } from "@prisma/client/edge";
declare global {
var prisma: PrismaClient | undefined;
}
const client = globalThis.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") globalThis.prisma = client;
export default client;this is also using prisma accelerate
@Ray hmm how does the auth.config.ts look like?
Giant pandaOP
this is auth.config.ts
auth.ts
import NextAuth from "next-auth";
import authConfig from "./auth.config";
import prisma from "@/lib/prisma";
import { PrismaAdapter } from "@auth/prisma-adapter";
export const {
handlers: { GET, POST },
auth,
} = NextAuth({
adapter: PrismaAdapter(prisma),
...authConfig,
});then you don't need accelerate with it I think
oh no wait
Giant pandaOP
auth is working fine now but redirects are not configured correctly imo
@Ray and this is auth.ts?
Giant pandaOP
yes
@Giant panda yes
put this on callback on auth.config.ts
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnLogin = nextUrl.pathname.startsWith("/login");
const isOnSignup = nextUrl.pathname.startsWith("/signup");
if (!isLoggedIn && isOnSignup) return true;
if (isLoggedIn && (isOnLogin || isOnSignup)) {
return Response.redirect(new URL("/the-url-you-want-to-redirect", nextUrl));
}
if (isLoggedIn) return true;
return false;
},Giant pandaOP
wait I tried something like this with next-auth v4 lol
does it work?
Giant pandaOP
// import Stripe from "stripe";
import Github from "next-auth/providers/github";
import prisma from "@/lib/prisma";
declare module "next-auth" {
// eslint-disable-next-line no-unused-vars
interface Session {
user: {
/** The user's id. */
id: string;
} & DefaultSession["user"];
}
}
import type { NextAuthConfig, DefaultSession } from "next-auth";
export default {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session, user }: { session: any; user: any }) {
session.user.id = user.id;
return session;
},
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnLogin = nextUrl.pathname.startsWith("/auth/signin");
// redirects config
if (!isLoggedIn && isOnLogin) {
return Response.redirect(new URL("/", nextUrl));
}
if (isLoggedIn) return true;
return false;
},
async redirect({
url,
baseUrl,
}: {
url: any | undefined;
baseUrl: any | undefined;
}) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
pages: {
signIn: "/auth/signin", // overrides the next-auth default signin page https://authjs.dev/guides/basics/pages
verifyRequest: "/auth/verify",
error: "/auth/error",
},
} satisfies NextAuthConfig;Giant pandaOP
it is not redirecting back to home page after signIn
if (isLoggedIn && isOnLogin) {
return Response.redirect(new URL("/", nextUrl));Giant pandaOP
why they force redirecing on layout
you have !isLoggedIn there
Giant pandaOP
oh
shit crashed "Uncaught TypeError: Error in input stream"
lol
Giant pandaOP
may be we need to manually handle the redirects on layout
seem like prisma accelerate thing
hmm yeah you could do that
ok so it is working when I manually redirect to home after signIn
import { Metadata } from "next";
import { redirect } from "next/navigation";
import { auth } from "../../../auth";
export const metadata: Metadata = {
title: "Authentication",
description: "Authentication forms built using the components.",
};
export default async function Layout({
children,
}: {
children: React.ReactNode;
}) {
const session = await auth();
if (session) redirect("/");
return (
<>
<div className="container relative h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0">
<div className="lg:p-8">
<div className="mx-auto flex flex-col justify-center space-y-6 w-[350px]">
{children}
</div>
</div>
</div>
</>
);
}you did it finally
Giant pandaOP
this is without extra callback thing
// import Stripe from "stripe";
import Github from "next-auth/providers/github";
import prisma from "@/lib/prisma";
declare module "next-auth" {
// eslint-disable-next-line no-unused-vars
interface Session {
user: {
/** The user's id. */
id: string;
} & DefaultSession["user"];
}
}
import type { NextAuthConfig, DefaultSession } from "next-auth";
export default {
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session, user }: { session: any; user: any }) {
session.user.id = user.id;
return session;
},
async redirect({
url,
baseUrl,
}: {
url: any | undefined;
baseUrl: any | undefined;
}) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
pages: {
signIn: "/auth/signin", // overrides the next-auth default signin page https://authjs.dev/guides/basics/pages
verifyRequest: "/auth/verify",
error: "/auth/error",
},
} satisfies NextAuthConfig;Giant pandaOP
this is weird
for home page callback url is different than dashboard page
@Giant panda for home page callback url is different than dashboard page
yes it will use callbackUrl
Giant pandaOP
"use client";
import { useEffect, useState } from "react";
import { signIn } from "next-auth/react";
import { Icons } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { usePathname, useSearchParams } from "next/navigation";
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {}
export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams();
const path = usePathname();
const handleSignIn = async () => {
setIsLoading(true);
await signIn("github", {
callbackUrl: searchParams.get("next") || path,
});
setIsLoading(false);
};
return (
<div className={cn("grid gap-6", className)} {...props}>
<Button
variant="outline"
type="button"
disabled={isLoading}
onClick={handleSignIn}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.gitHub className="mr-2 h-4 w-4" />
)}{" "}
Github
</Button>
</div>
);
} so for dashboard page callback url is "http://localhost:3000/auth/signin?next=/dashboard/I think you can remove the next
callbackUrl: searchParams.get("next") || path,
});remove this if you don't want this behaviour
Giant pandaOP
remove the callbackurl ?
yes
or just put
/Giant pandaOP
ok
"use client";
import { useEffect, useState } from "react";
import { signIn } from "next-auth/react";
import { Icons } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { usePathname, useSearchParams } from "next/navigation";
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {}
export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams();
const path = usePathname();
const handleSignIn = async () => {
setIsLoading(true);
await signIn("github", {
callbackUrl: "/",
});
setIsLoading(false);
};
return (
<div className={cn("grid gap-6", className)} {...props}>
<Button
variant="outline"
type="button"
disabled={isLoading}
onClick={handleSignIn}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.gitHub className="mr-2 h-4 w-4" />
)}{" "}
Github
</Button>
</div>
);
}show the code in dashboard
I think you have
?next= in the redirect there?Giant pandaOP
lol yes
import { redirect } from "next/navigation";
import React, { useMemo } from "react";
import { auth } from "../../../../auth";
import { cn } from "@/lib/utils";
import Logout from "@/components/buttons";
async function Dashboard() {
const session = await auth();
if (!session) {
redirect("/auth/signin?next=/dashboard/");
}
return (
<div className="p-8 ">
<div className="relative">
<h1 className="pb-4 font-medium text-xl">Welcome to Dashboard</h1>
<div className="absolute top-0 right-0">
<Logout />
</div>
</div>
<AuthStatus
status={session ? Status.AUTHENTICATED : Status.UNAUTHENTICATED}
/>
</div>
);
}
enum Status {
AUTHENTICATED,
UNAUTHENTICATED,
}
const statusClasses = {
[Status.AUTHENTICATED]: "text-green-600",
[Status.UNAUTHENTICATED]: "text-red-600",
};
const AuthStatus = ({ status }: { status: Status }) => {
const authStatus = useMemo(() => statusClasses[status] || "", [status]);
return (
<div className="p-2 ">
<p className={cn(authStatus, "font-medium ")}>
User is{" "}
{status === Status.AUTHENTICATED ? "Authenticated" : "Unauthenticated"}
</p>
</div>
);
};
export default Dashboard;I think that is not much of a problem
