I have a code, where I want to get the cookies from the user who is on the front end and check if it is the same as the bano, as I have the jwt token in the database and in the cookies on the front end, as I check if the "token" cookie exists, If it doesn't exist, it redirects you to login, if it exists, it checks if the cookie matches the bank's cookie, if it does, it releases the page, if it doesn't, it gives an invalid token. code down
"use client"
import { redirect } from 'next/navigation'
import {cookies } from "next/headers"
import { useContext } from 'react'
import { AuthContext } from '../contexts/AuthContext'
export default function ExploreCourses(){
const {user} = useContext(AuthContext)
if(!user.token){
redirect("/signIn")
}
if(user.token){
const cookie = cookies().get("token")
if(!cookie == user.token){
redirect("/signIn")
}
return
}
return(
<h2>dashboard</h2>
)
}
** error: ReactServerComponentsError:
You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component. Learn more: https://nextjs.org/docs/getting-started/react-essentials **
Now, I want to know why it gives this error, I already tried using nookies, but to do this check I would need the getServerSideProps function, and so check, but it is not available because I am using the app/ directory, because it gives this error ? and how could I do this check? I'm new using next.js
You-re using a server only function (headers) inside a client component. You should remove "use client" at the top of your file, and on all of parent's component. If you need client interactivity you can create a child client component. For example
in another file
in the example above YourClientComponent is marked as "use client". You can pass the props to access the data loaded on the server. Hope this will help.