How do I handle the user session when I using next-auth.js
Unanswered
Champagne D’Argent posted this in #help-forum
Champagne D’ArgentOP
import NextAuth, { NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
import { prisma } from "./prisma/prisma"
import { PrismaAdapter } from "@auth/prisma-adapter";
const GOOGLE_CLIENT_ID = process.env.GOOGLE_AUTH_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_AUTH_SECRET;
const config = {
adapter: PrismaAdapter(prisma),
providers: [
Google({
clientId: process.env.GOOGLE_AUTH_ID,
clientSecret: process.env.GOOGLE_AUTH_SECRET,
}),
],
basePath: "/auth/",
callbacks: {
},
};
export const { handlers, auth, signIn, signOut } = NextAuth(config)However, after I login the page redirects to http://localhost:3000/auth/callback/google?
where I get the authentication code and everything. I am a little confused on how I am supposed to handle this state and store it
12 Replies
Champagne D’ArgentOP
import LoginForm from "./auth-components";
import { auth } from "../../auth";
export default async function AuthPage() {
const session = await auth();
return (
<>
<div className="bg-base-100">
<div className="container flex items-center justify-center align-middle mx-auto h-screen">
{session ? (
<>
<div className="bg-neutral flex flex-col space-y-4 p-10 rounded-md">
<h1 className="font-semibold text-white w-64 mb-4">
Welcome, {session?.user.name}
</h1>
<h1 className="font-semibold text-white w-64 mb-4">
You are logged in with {session?.user.email}
</h1>
<h1 className="font-semibold text-white w-64 mb-4">
Your token expires at {session?.expires}
</h1>
</div>
</>
) : (
<>
<div className="bg-neutral flex flex-col space-y-4 p-10 rounded-md">
<h1 className="font-semibold text-white w-64 mb-4">
We are currently using google Oauth for our Authentication.
Sign up if you are a first time user or Login if you are
returning to our application.
</h1>
<LoginForm />
</div>
</>
)}
</div>
</div>
</>
);
}This is my login page right now
Brown bear
You can handle user session from useSession hook
like this
import { useSession } from "next-auth/react";const { data: session } = useSession();Also for page authentication, you will need to use
SessionProviderChampagne D’ArgentOP
Thanks a lot!
I will test this out soon and get back to you
Champagne D’ArgentOP
After the user login the page is redirected to localhost:3000/auth/google/callback?[access token stuff here]. Do I have to make a route to handle this?
Brown bear
No need, next-auth would be handle callback link itself
Champagne D’ArgentOP
I had put the incorrect path: I omitted api from the correct redirect path api/auth/google/callback