Next.js Discord

Discord Forum

Cookie-Based Authentication

Answered
American black bear posted this in #help-forum
Open in Discord
Avatar
American black bearOP
I hope any of you can help me!

I am using nextjs13 with approuter.
I have a python backend API with cookie-based authentication. (NOT using nextauth)
I can't SSR calling the API because client cookies are not sent to server which is not sending to my python backend.

How can I make this work?

Thanks for reading!
Answered by American black bear
I fixed it!
For everyone having the same issue, you can send a cookie via headers this way, I don't know if this is a good practice or not, but its working, I'll be glad if someone could correct me so I can learn a better way to do this




import { cookies } from "next/headers";

export async function getData() {
const nextCookies = cookies();
console.log("nextCookies", nextCookies.get("sAccessToken").value);
const data = fetch("http://localhost:8000/api/post", {
headers: {
"Content-Type": "application/json",
cookie: sAccessToken=${nextCookies.get("sAccessToken").value},
},
withCredentials: true,
// credentials: "include",
credentials: "same-origin",
}).then((res) => {
console.log("res", res);
return res.json();
});
return data;
}
View full answer

4 Replies

Avatar
American black bearOP
I fixed it!
For everyone having the same issue, you can send a cookie via headers this way, I don't know if this is a good practice or not, but its working, I'll be glad if someone could correct me so I can learn a better way to do this




import { cookies } from "next/headers";

export async function getData() {
const nextCookies = cookies();
console.log("nextCookies", nextCookies.get("sAccessToken").value);
const data = fetch("http://localhost:8000/api/post", {
headers: {
"Content-Type": "application/json",
cookie: sAccessToken=${nextCookies.get("sAccessToken").value},
},
withCredentials: true,
// credentials: "include",
credentials: "same-origin",
}).then((res) => {
console.log("res", res);
return res.json();
});
return data;
}
Answer
Avatar
Asiatic Lion
thats a good way to do it yes for cross site
Avatar
American black bearOP
Thank you very much, I mark this as solved
Avatar
set "cookie"