Reputation: 138
My primary goal is to be able to use middleware to redirect users to the login/signup pages when they are not authenticated. I'd also like to be able to do things like check if the user is logged in before they are directed to the login page so that I can just redirect them right away. I originally wanted to do this without the use of next-auth because I wanted to learn how authentication works but I can't use crypto in the edge environment so next-auth was my second choice.
What I'm having issues with is checking the session in any part of my application. Currently I have the login flow setup, with appropriate client id/secret from Google (the only provider I'm using for this proj). The user can click login, is taken to a Google login page, login with their Google acct, then is redirected back to the default endpoint.
The button click leads to to the Google login page via the signin('google')
function.
Then in app/api/[...nextauth]/route.ts:
import NextAuth from "next-auth";
import { authOptions } from "./auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST};
And app/api/[...nextauth]/auth.ts:
import GoogleProvider from 'next-auth/providers/google'
import { AuthOptions, getServerSession } from "next-auth"
const authOptions: AuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
}
const getSession = () => getServerSession(authOptions)
export { authOptions, getSession }
And in app/api/callback/google/route.ts (just redirects to homepage)
import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
return Response.redirect(`${process.env.BASE_URL}/`);
}
middleware.ts:
import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET });
console.log(token);
return NextResponse.next();
}
export const config = {
matcher: ['/'],
}
package.json:
"dependencies": {
"dotenv": "^16.4.7",
"googleapis": "^144.0.0",
"next": "15.1.3",
"next-auth": "^4.24.11",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"slonik": "^46.4.0",
"zod": "^3.24.1"
},
To try and access the session I am using getServerSession(authOptions)
on server side components.
On client side components I am using the hook useSession()
to get the session.
I've been trying multiple different setups from guides online and I just can't seem to get it right. Any help as to why the sessions always are null would be greatly appreciated.
Upvotes: 1
Views: 58