Open CesarBenavides777 opened 2 months ago
I think it has something to do with how the Server object is passed into the tokenHandler when logged locally I see the full server object but when logged on production it doesn't seem to get the NextResponse
object/constructor.
Production:
server Object [Module] {}
Locally:
server Object [Module] {
ImageResponse: [Getter],
NextRequest: [Getter],
NextResponse: [Getter],
URLPattern: [Getter],
unstable_after: [Getter],
userAgent: [Getter],
userAgentFromString: [Getter]
}
For some reason production builds don't have access to this?
I think importing NextResponse
directly inside the tokenHandler seems to fix it!!!!
Patched this file
experimental-app-router/dist/server/routeHandler/tokenHandler.js
import { cookies } from 'next/headers.js';
import { getWpUrl, getWpSecret } from '../../faust-core-utils.js';
import { NextResponse } from 'next/server';
export async function tokenHandler(req, s) {
var _a, _b;
try {
const secretKey = getWpSecret();
if (!secretKey) {
throw new Error('FAUST_SECRET_KEY must be set');
}
const { url } = req;
const code = (_a = new URL(url).searchParams.get('code')) !== null && _a !== void 0 ? _a : undefined;
const cookieStore = cookies();
const cookieName = `${getWpUrl()}-rt`;
const refreshToken = (_b = cookieStore.get(cookieName)) === null || _b === void 0 ? void 0 : _b.value;
if (!refreshToken && !code) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: {
'Content-Type': 'application/json',
},
});
}
const wpFaustAuthorizeEndpoint = `${getWpUrl()}/?rest_route=/faustwp/v1/authorize`;
const response = await fetch(wpFaustAuthorizeEndpoint, {
headers: {
'Content-Type': 'application/json',
'x-faustwp-secret': secretKey,
},
method: 'POST',
body: JSON.stringify({
code,
refreshToken,
}),
});
// Log response status and body
console.log('Response status:', response.status);
const responseBody = await response.text();
console.log('Response body:', responseBody);
if (!response.ok) {
// @TODO Delete the cookie
// cookieStore.delete(cookieName);
// @TODO throw different errors based on response
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: {
'Content-Type': 'application/json',
},
});
}
const data = JSON.parse(responseBody);
const res = new NextResponse(JSON.stringify(data), { // Ensure correct usage
status: 200,
});
console.log("data", data);
console.log("res", res);
res.cookies.set(cookieName, data.refreshToken, {
secure: true,
httpOnly: true,
path: '/',
expires: new Date(data.refreshTokenExpiration * 1000),
sameSite: 'lax',
});
return res;
} catch (err) {
console.error('Invalid response for authorize handler:', err);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
}
I also updated the useFormState
hook to useActionState
using React 19 and Next 15 RCs. On the login page.
"use client";
import { useFormStatus } from "react-dom";
import { useActionState } from "react";
import { loginAction } from "./action";
function SubmitButton() {
const status = useFormStatus();
return (
<button disabled={status.pending}>
{status.pending ? "Loading..." : "Login"}
</button>
);
}
export default function Page() {
const [state, formAction] = useActionState(loginAction, {});
return (
<>
<h2>Login</h2>
<form action={formAction}>
<fieldset>
<label htmlFor="usernameEmail">Username or Email</label>
<input type="name" name="usernameEmail" />
</fieldset>
<fieldset>
<label htmlFor="password">Password</label>
<input type="password" name="password" />
</fieldset>
<SubmitButton />
{state.error && (
<p dangerouslySetInnerHTML={{ __html: state.error }}></p>
)}
</form>
</>
);
}
@CesarBenavides777 Thank you I will take a look. I remember we had to provide a workaround at one point https://github.com/wpengine/faustjs/commit/42ded8091e0025828638dbf149777c876a0559b2
in order to fix some build issues. I think Vercel is messing around with those runtimes. It does not make sense that this is happening. I will check your solution as well.
FYI, I'm using experimental app router with the same dependencies listed here and am not having any issues on a production instance on vercel. Is there perhaps a vercel configuration that you @CesarBenavides777 has set that might be interfering here? We're not using any of the premium vercel features at this point.
@cwhatley
Nothing outside the ordinary:
Maybe not using npm or yarn? Using bun currently
I'm using yarn + corepack, node 20.x and have the same env vars set.
I do have a monorepo, so my build + start look like:
corepack enable && yarn workspace XXX build
and yarn workspace XXX start
I am experience the same issue when deploying to vercel, let me know if you find a fix!
I have the same problem on Vercel and Netlify
Description
As a user I want to be able to use the onLogin function to properly log in and see the my-account page using the
@faustwp/experimental-app-router
package. The implementation shown in the example directory does in fact work with local development as intended. But when deployed to production on vercel you get a:Steps to reproduce
.env
filebun dev
/login
page and log inAdditional context
Related Discord discussion: https://discord.com/channels/836253505944813629/1233495010440122419
Vercel Error Logs:
@faustwp/core Version
^3.0.3
@faustwp/cli Version
^3.0.2
FaustWP Plugin Version
1.3.2
WordPress Version
6.5.5
Additional environment details
Deployed on Vercel WordPress is on instaWP
Cookies have been confirmed to work across domains.
WPGraphQL JWT Auth does in fact break this because of a
wrong number of segments
FYILinks: CMS: https://cms.cesarbenavides.com Frontend: https://staging.cesarbenavides.com
Using the WPGraphQL CORS plugin for additional testing (doesn't work when installed or uninstalled)
Please confirm that you have searched existing issues in the repo.