readme
readme
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
nvm i found the error @Ages @TotalScrub I named my file route..js instead of route.js. You can close this thread now. Thank you for your help.
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
No description
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
No description
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
i have also verified that the token is valid by copy pasting my token to the kinde jwt decoder website.
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
after the middleware i directly have my route.js
import { db } from "@/config/firebase";
import { getReceipt } from "@/helpers/getReceipt";
import { NextResponse } from "next/server";

export const PUT = async (req, { params }) => {
try {
console.log(req)
const data = await req.json();
const receiptId = params.id;
const receiptRef = db.collection("receipts").doc(receiptId);
await receiptRef.update(data);

const updatedReceipt = await getReceipt(receiptId)

return NextResponse.json(
{
message: "Receipt updated successfully",
receipt: updatedReceipt,
},
{ status: 200 }
);
} catch (error) {
console.log(error);
return NextResponse.json(
{
error: "Error updating image",
},
{ status: 400 }
);
}
};

import { db } from "@/config/firebase";
import { getReceipt } from "@/helpers/getReceipt";
import { NextResponse } from "next/server";

export const PUT = async (req, { params }) => {
try {
console.log(req)
const data = await req.json();
const receiptId = params.id;
const receiptRef = db.collection("receipts").doc(receiptId);
await receiptRef.update(data);

const updatedReceipt = await getReceipt(receiptId)

return NextResponse.json(
{
message: "Receipt updated successfully",
receipt: updatedReceipt,
},
{ status: 200 }
);
} catch (error) {
console.log(error);
return NextResponse.json(
{
error: "Error updating image",
},
{ status: 400 }
);
}
};

14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
i do not have any token verification configured for this route after the middleware stage. Also after updating as you can see the message has changed to getUser [TypeError: Cannot read properties of null (reading 'sub')]. Which could mean that the wherever this additiional step is taking place it is returing null after decoding the token.
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
No description
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
Yes I am sending the exact same header for the edit requests. I’ve named it x-kinde-token . Even when I log the token in the middleware the token and tye resultant decoded header both get logged. And after the middleware I don’t really have a auth check for this route. So idk where is this extra getUser check being made and instead of a 200 I get a 405 method not allowed
14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
middleware.js
import { NextResponse } from "next/server";
import { decode } from "jsonwebtoken";

export default async function middleware(req) {
const token = req.headers.get("x-kinde-token");

if (!token) {
return NextResponse.json({ error: "No Token provided" }, { status: 401 });
}

const { header } = decode(token, { complete: true });

const headersExist = header && Object.keys(header).length !== 0;

if (!headersExist) {
return NextResponse.json({ error: "Incorrect Token Provided" }, { status: 401 });
}

const requestHeaders = new Headers(req.headers);
requestHeaders.set('x-kinde-header', JSON.stringify(header));
requestHeaders.set('x-kinde-token', token);

const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});

return response;
}

export const config = {
matcher: ["/api/receipts/:path*"],
};
import { NextResponse } from "next/server";
import { decode } from "jsonwebtoken";

export default async function middleware(req) {
const token = req.headers.get("x-kinde-token");

if (!token) {
return NextResponse.json({ error: "No Token provided" }, { status: 401 });
}

const { header } = decode(token, { complete: true });

const headersExist = header && Object.keys(header).length !== 0;

if (!headersExist) {
return NextResponse.json({ error: "Incorrect Token Provided" }, { status: 401 });
}

const requestHeaders = new Headers(req.headers);
requestHeaders.set('x-kinde-header', JSON.stringify(header));
requestHeaders.set('x-kinde-token', token);

const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});

return response;
}

export const config = {
matcher: ["/api/receipts/:path*"],
};
/api/receipts/edit/[id]/route.js
import { db } from "@/config/firebase";
import { getReceipt } from "@/helpers/getReceipt";
import { NextResponse } from "next/server";

export const POST = async (req, { params }) => {
try {

const data = await req.json();
const receiptId = params.id;
const receiptRef = db.collection("receipts").doc(receiptId);
await receiptRef.update(data);

const updatedReceipt = await getReceipt(receiptId)

return NextResponse.json(
{
message: "Receipt updated successfully",
receipt: updatedReceipt,
},
{ status: 200 }
);
} catch (error) {
console.log(error);
return NextResponse.json(
{
error: "Error updating image",
},
{ status: 400 }
);
}
};

import { db } from "@/config/firebase";
import { getReceipt } from "@/helpers/getReceipt";
import { NextResponse } from "next/server";

export const POST = async (req, { params }) => {
try {

const data = await req.json();
const receiptId = params.id;
const receiptRef = db.collection("receipts").doc(receiptId);
await receiptRef.update(data);

const updatedReceipt = await getReceipt(receiptId)

return NextResponse.json(
{
message: "Receipt updated successfully",
receipt: updatedReceipt,
},
{ status: 200 }
);
} catch (error) {
console.log(error);
return NextResponse.json(
{
error: "Error updating image",
},
{ status: 400 }
);
}
};

14 replies
KKinde
Created by readme on 11/19/2024 in #💻┃support
Invalid Token Error
Just to give an idea of my code and workflow im attaching the code Modal.jsx worker method
const handleSubmitEditPayment = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);

formData.append("paymentInfo.method", method);
formData.append("paymentInfo.status", status);

await sendUpdateReceipt(id, formData)
.then((result) => console.log(result))
.catch((error) => console.log(error));
};
const handleSubmitEditPayment = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);

formData.append("paymentInfo.method", method);
formData.append("paymentInfo.status", status);

await sendUpdateReceipt(id, formData)
.then((result) => console.log(result))
.catch((error) => console.log(error));
};
sendUpdateReceipt.js
"use server";

import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";

export const sendUpdateReceipt = async (id, formData) => {
try {
const { getAccessTokenRaw } = getKindeServerSession();
const token = await getAccessTokenRaw();

const data = {};
formData.forEach((value, key) => {
data[key] = value;
});

const response = await fetch(`http://localhost:3000/api/receipts/edit/${id}`, {
method: "POST",
headers: {
"x-kinde-token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(data),
});

if (response.ok) {
const result = await response.json();
return result;
} else {
const errorResult = await response.json();
return { error: errorResult.error };
}
} catch (error) {
return {
error,
};
}
};
"use server";

import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";

export const sendUpdateReceipt = async (id, formData) => {
try {
const { getAccessTokenRaw } = getKindeServerSession();
const token = await getAccessTokenRaw();

const data = {};
formData.forEach((value, key) => {
data[key] = value;
});

const response = await fetch(`http://localhost:3000/api/receipts/edit/${id}`, {
method: "POST",
headers: {
"x-kinde-token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(data),
});

if (response.ok) {
const result = await response.json();
return result;
} else {
const errorResult = await response.json();
return { error: errorResult.error };
}
} catch (error) {
return {
error,
};
}
};
14 replies
KKinde
Created by readme on 10/28/2024 in #💻┃support
Next.js Refresh Token null
@Daniel_Kinde sorry for the late reply. I wrapped the application and now i can see the refresh tokens. But when should i use it. I know that they must be used when the previous token gets expired but where in the application should one use it. Thank you.
7 replies
KKinde
Created by readme on 10/28/2024 in #💻┃support
Next.js Refresh Token null
i am also attaching my code for reference
import { db } from "@/config/firebase";
import { decodeToken } from "@/helpers/decodeToken";
import { NextResponse } from "next/server";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";

export const GET = async (req) => {
try {

const {refreshTokens} = getKindeServerSession();

const tokens = await refreshTokens(req);
console.log(tokens)

const { sub: user, error } = await decodeToken(req);

if (error) {
return NextResponse.json({ error: "Not a valid token" }, { status: 401 });
}

const { searchParams } = new URL(req.url);
const pageSize = parseInt(searchParams.get("pageSize") || "5", 10);

let query = db
.collection("receipts")
.where("user", "==", user)
.limit(pageSize);

const receipts = await query.get();

if (receipts.empty) {
return NextResponse.json({ data: [], message: "No more data." });
}

const data = receipts.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));

return NextResponse.json({
data,
message: "Data fetched successfully.",
});
} catch (error) {
console.error("Error fetching receipts:", error);
return NextResponse.json(
{ error: "Failed to fetch receipts." },
{ status: 500 }
);
}
};
import { db } from "@/config/firebase";
import { decodeToken } from "@/helpers/decodeToken";
import { NextResponse } from "next/server";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";

export const GET = async (req) => {
try {

const {refreshTokens} = getKindeServerSession();

const tokens = await refreshTokens(req);
console.log(tokens)

const { sub: user, error } = await decodeToken(req);

if (error) {
return NextResponse.json({ error: "Not a valid token" }, { status: 401 });
}

const { searchParams } = new URL(req.url);
const pageSize = parseInt(searchParams.get("pageSize") || "5", 10);

let query = db
.collection("receipts")
.where("user", "==", user)
.limit(pageSize);

const receipts = await query.get();

if (receipts.empty) {
return NextResponse.json({ data: [], message: "No more data." });
}

const data = receipts.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));

return NextResponse.json({
data,
message: "Data fetched successfully.",
});
} catch (error) {
console.error("Error fetching receipts:", error);
return NextResponse.json(
{ error: "Failed to fetch receipts." },
{ status: 500 }
);
}
};
7 replies