I used firebase authentication’s method signInWithEmailAndPassword in login api routes and user authenticated with this. Then I want to get user information with get-user api routes. I used auth in get-user api route. When user authenticates with login api routes auth has currentUser but when I want to get currentUser with auth in get-user api route I can’t see currentUser in auth so I want to fetch with get-user api route I always see user as null
/api/auth/login
// import { signInFB } from '@/app/libs/user';
import { NextResponse } from 'next/server';
import { serialize } from 'cookie';
import { SignJWT } from 'jose';
import { auth } from '@/app/libs/firebase';
import { signInWithEmailAndPassword } from 'firebase/auth';
const JWT_TOKEN = new TextEncoder().encode(process.env.JWT_SECRET!);
export const POST = async (req: Request) => {
if (req.method !== 'POST') return NextResponse.json({ message: 'Invalid method' }, { status: 401 });
try {
const { email, password } = await req.json();
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
if (!user) return NextResponse.json({ message: 'giriş başarılı' }, { status: 401 });
const payload = {
id: user.uid,
email: user.email,
};
const token = await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('1h')
.sign(JWT_TOKEN);
const response = NextResponse.json({ message: 'giriş başarılı', user }, { status: 200 });
const cookie = serialize('authToken', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/',
maxAge: 60 * 60,
});
response.headers.append('Set-Cookie', cookie);
return response;
} catch (error) {
console.log('error:', error);
return NextResponse.json({ message: 'giriş başarılı' }, { status: 500 });
}
};
export const runtime = 'nodejs';
/api/auth/get-user
import { auth } from '@/app/libs/firebase';
import { getUserFromFS } from '@/app/libs/user';
import { NextRequest, NextResponse } from 'next/server';
export const GET = async (req: NextRequest) => {
if (req.method !== 'GET') return NextResponse.json({ message: 'Invalid method' }, { status: 401 });
const user = auth.currentUser;
if (user) {
const fetchedUser = await getUserFromFS(user.uid);
return NextResponse.json({ fetchedUser }, { status: 200 });
}
return NextResponse.json({ message: 'No user!' }, { status: 401 });
};
getUserFromFS function:
export const getUserFromFS = async (uid: string) => {
try {
const userDocRef = doc(db, 'users', uid);
const userRef = await getDoc(userDocRef);
if (userRef.exists()) {
return userRef.data() as userProfile;
} else {
return null;
}
} catch (error) {
if (error instanceof FirebaseError) {
// Hata türü FirebaseError ise hatayı olduğu gibi fırlatıyoruz
throw error;
} else {
// FirebaseError değilse genel bir hata olarak fırlatıyoruz
throw new Error('An unexpected error occurred');
}
}
};
I am expecting getting user information