Client to server navigation
Unanswered
evandabest posted this in #help-forum
Hey guys, I just got started with using NextJs and I ran into this problem. I am trying to navigate from a client component to a server component but redirect nor useRouter is working. The code is below...
/login is a server component. I do have middleware set up. if there is another approach to this problem, please let me know. Thank you guys
"use client";
import { createClient } from "@/utils/supabase/client";
import { useEffect, useState } from "react";
import { redirect } from "next/navigation";
import { useRouter } from "next/router";
const Home = () => {
const [user, setUser] = useState<any>(null);
const supabase = createClient();
const router = useRouter()
useEffect(()=> {
const fetchUser = async() => {
const { data, error } = await supabase.auth.getUser()
if (error || !data?.user) {
router.push('/login')
} else {
setUser(data)
}
}
fetchUser();
}, [])
const signOutUser = async() => {
await supabase.auth.signOut();
router.push('/login')
}
if (!user) {
return null;
}
return (
<>
<p> Welcome {user.user.email}</p>
<button onClick={signOutUser}>Logout</button>
</>
)
}
export default Home/login is a server component. I do have middleware set up. if there is another approach to this problem, please let me know. Thank you guys
8 Replies
American Crow
Any particular reason you don't auth on the server?
import { createClient } from '@/utils/supabase/server' // <- Imported form /server
import { redirect } from 'next/navigation'
export default async function Page() {
const supabase = createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
return <YourClientComponentWithMuchInteractivity user={user} />
}Hmm I’ll try that but I intended this home page to be a client component
American Crow
Well replace
<YourClientComponentWithMuchInteractivity> with <HomePage />.Japanese flying squid
import { useRouter } from "next/router";
you have to use useRouter from "next/navigation"
you have to use useRouter from "next/navigation"