Server becomes unresponsive after redirecting with code 307 (in dev only)
Unanswered
Palomino posted this in #help-forum
PalominoOP
I try to redirect a user to "/" after authorizing, I have tried alot but it seems to be whenever a redirect happens..
Ping me if you write something, as I dont check very often 😄
import { NextRequest, NextResponse } from "next/server";
import addUserToDb from "@/utils/functions/addUserDb";
import getDiscordUserInfo from "@/utils/functions/exchangeDiscordToken";
import jwt from "jsonwebtoken";
import redis from "@/utils/connections/redis";
import session from "@/utils/functions/sessionCookieEncryptions";
import { type RESTGetAPIUserResult } from "discord-api-types/v10";
export async function GET(req: NextRequest) {
const code = req.nextUrl.searchParams.get("code");
const type = req.nextUrl.searchParams.get("type");
if (!code || !type) {
return NextResponse.json({ error: "Missing authorization details." });
}
let res, userInfo, setCookies = false, cookieData = "";
if (type === "discord") {
userInfo = await getDiscordUserInfo(code).catch((err) => {
if (err.message.includes("400")) {
res = NextResponse.json({ error: "Invalid authorization code." });
}
});
if (!res) {
userInfo = null;
} else {
const userId = await (async (user: RESTGetAPIUserResult) => {
try {
if (!user) return null;
const { status, userId } = await addUserToDb({ type: "discord", user });
return (status && userId) ? session.encrypt(userId) : { status, userId };
} catch {
return null;
}
})(userInfo);
if (typeof userId === "string") {
setCookies = true;
cookieData = userId;
} else {
const errCode = `${Math.random()}${Date.now()}`;
await redis.set(`forum:error:${errCode}`, JSON.stringify(userId), { EX: 86400 });
res = NextResponse.redirect(new URL(`/error.php?code=${errCode}`, process.env.NEXT_PUBLIC_URL_ENV));
}
}
}
if (!res) res = NextResponse.redirect(new URL("/", process.env.NEXT_PUBLIC_URL_ENV));
if (setCookies) {
res.cookies.set("session", jwt.sign(cookieData, process.env.COOKIE_SECRET!), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
path: "/",
domain: process.env.NEXT_PUBLIC_URL_ENV!.replace(/https?:\/\//, "").replace("/", ""),
maxAge: 172800,
});
redis.set(`session:forum:${cookieData}`, Date.now().toString(), { EX: 172800 });
}
return res || NextResponse.json({ error: "An unexpected error occurred." });
}
This code is abit messy, but this is the principle. I have looked at this for a while and still dont understand where it goes wrong. It works when I push the code to my production server, which uses cloduflare tunnels. the server for dev is pointed to local.mydomain.tld, which is just 127.0.0.1Ping me if you write something, as I dont check very often 😄
1 Reply
PalominoOP
Forgot to add that server is on, but website still appears off