I just posted to production. Been developing local...
# support-questions
f
I just posted to production. Been developing localhost with nextjs. When in production I'm getting this error:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I'm wondering if it has something to do with
NextCors
middleware? Any ideas?
a
hi
So that means in prod, when your frontend sends a request to Nextjs
and Nextjs responses with a 3xx code
hence, the redirect
but
on OPTIONS requests, it shouldnt respond with 3xx
rather, it should be a 2xx
f
sorry, false alarm, here is the code I thought might be the answer... await NextCors(req, res, { methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"], origin: "*", //process.env.NEXT_PUBLIC_HOST, credentials: true, allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], }); I changed "origin" to "*" instead of the commented out code
a
Hm
f
here is the other part to error
POST https://finicky.pet/api/auth/session/refresh net::ERR_FAILED
a
Does the NEXT_PUBLIC_HOST end with a "/" ?
f
so, I assume it's in supertokens auth
which is where that NextCors code is
a
.
f
here's the firefox error `
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://finicky.pet/api/auth/session/refresh. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://finicky.pet/api/auth/session/refresh. (Reason: CORS request did not succeed). Status code: (null).`
a
Let me try pinging the api
What method does it use?
HTTP method
f
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
r
You should add an origin btw. Not use *
a
Yeah
Cuz bad security in prod
f
ok, so back to orig. config
origin: process.env.NEXT_PUBLIC_HOST,
a
Getting a 500 with options
An options preflight should always have a 2xx for CORS to succeed
r
with nextjs, you don't even need CORS if your frontend and backend have the same domain
a
Yop
f
well, just going by the supertokens example
cause it's new to me
a
*unless u are cringe like me and decide to host the frontend separately cuz why tf not*
im new to supertokens as well
r
Is the browser making an OPTIONS request?
a
It should, cuz it's firefox
It says it received a preflight response which is a redirect, which should mean its sending an OPTIONS
f
I have my _app.js wrapped in IF THAT means anything
r
that's odd. it shouldn't send an OPTIONS call if the domain is the same
that shouldn't make a diff
f
my _app.js
Copy code
if (typeof window !== "undefined") {
  // we only want to call this init function on the frontend, so we check typeof window !== 'undefined'
  SuperTokensReact.init(frontendConfig());
}

const EmailPasswordAuthNoSSR = dynamic(
  new Promise((res) => res(EmailPassword.EmailPasswordAuth)),
  { ssr: false }
);

export default function App({ Component, pageProps }) {
  const securityLevel = Component.securityLevel;
  const getLayout = Component.getLayout || ((page) => page);

  if (securityLevel === "full") {
    return (
      <EmailPasswordAuthNoSSR>
        {getLayout(<Component {...pageProps} />)}
      </EmailPasswordAuthNoSSR>
    );
  } else {
    return (
      <EmailPasswordAuthNoSSR requireAuth={false}>
        {getLayout(<Component {...pageProps} />)}
      </EmailPasswordAuthNoSSR>
    );
  }
}
r
What is the value of api domain and website domain on the frontend config?
f
Copy code
export const appInfo = {
  // learn more about this on https://supertokens.com/docs/emailpassword/appinfo
  appName: "finicky.pet-v4",
  apiDomain: process.env.NEXT_PUBLIC_HOST,
  websiteDomain: process.env.NEXT_PUBLIC_HOST,
  apiBasePath: "/api/auth",
  websiteBasePath: "/auth",
};
r
what what is the value of
process.env.NEXT_PUBLIC_HOST
?
a
I asked that as well
I was wondering what it was
Because that could be the culprit
f
a
http??
But your API is https
wait, why dont u change the next public host to https?
change it to this
Because the API u are trying to ping is on HTTPS, and when u are visiting ur site i think that's probably ur HTTPS frontend as well
f
sorry, it is https
a
Oh okay
f
there's a supertokens redirect on frontendconfig() but should not have been touched in this landing page
a
But here's my question
if its redirecting on prod, why not local?
r
What have you added in the origin part of the cors config?
a
Because if some sort of redirect was actually coded, it shouldve redirected on local as well
f
Copy code
appInfo,
    recipeList: [
      EmailPasswordReact.init({
        getRedirectionURL: async (context) => {
          if (context.action === "SUCCESS") {
            if (context.redirectToPath !== undefined) {
              // navigate back to where the user was before authenticated
              return context.redirectToPath;
            }
            return "/dashboard";
          }
          return undefined;
        },
r
this
f
this is /api/auth/[[...path]].js
r
your website is actually on www.finicky.pet So your websiteDomain should be www.finicky.pet everywhere
a
And the only type of unwanted/unpredictable redirect i know of is when u send the request to an HTTP server, but it redirects to HTTPS. It might be that the frontend is sending the request to http and the server is redirecting it to https on frontend
f
Copy code
supertokens.init(backendConfig());

export default async function superTokens(req, res) {
  // NOTE: We need CORS only if we are querying the APIs from a different origin
  await NextCors(req, res, {
    methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
    origin: process.env.NEXT_PUBLIC_HOST,
    credentials: true,
    allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],
  });

  await superTokensNextWrapper(
    async (next) => {
      await middleware()(req, res, next);
    },
    req,
    res
  );
  if (!res.writableEnded) {
    res.status(404).send("Not found");
  }
}
a
Just a hypothesis
might be wrong
r
and allowed origin on backend should be www.finicky.pet too
a
so its not the same domain everywhere?
f
so can I use
process.env.NEXT_PUBLIC_HOST
?
r
you need to use www.finicky.pet as the websiteDomain.
a
Which is the NEXT_PUBLIC_HOST
f
RIGHT
r
If process.env.NEXT_PUBLIC_HOST !== www.finicky.pet, then you cant use process.env.NEXT_PUBLIC_HOST
a
So just change that
f
appName: "finicky.pet-v4", apiDomain: process.env.NEXT_PUBLIC_HOST, websiteDomain: process.env.NEXT_PUBLIC_HOST, apiBasePath: "/api/auth", websiteBasePath: process.env.NEXT_PUBLIC_HOST,
r
yup.. but the apiDomain needs to be finicky.pet
f
what about "apiBasePath", that's prolly good as is
a
um
@rp
r
cause that's where your API is.. unless it can work on www.finicky.pet/api/.. as well
a
the api
is also returning www.finicky.pet
here's the redirect
u sending requestt to finicky.pet, redirecting to www.finicky.pet
r
well yea.. so then just update process.env.NEXT_PUBLIC_HOST to https://www.finicky.pet
a
That's probaby the culprit
f
(is that Postman)?
a
No, firefox devtools
i was checking if there was any redirects there
f
let you know in a sec
a
and there's one
that's because you are sending the request to finicky.pet, but its redireting to www.finicky.pet
do this @funk101
f
still failing
a
Is the API domain set to same?
Make sure every single domain you have is set to www.finicky.pet
f
no
/api/auth
a
im talking about the domain
the api domain
f
yes, set to same
a
next public host is now https://www.finicky.pet/ ?
Could you try removing the / ?
https://www.finicky.pet
no slash at the end
r
The / shouldn't matter
a
because ive had issues with that once
Im just sayibng from my experienc when i used next
single slash ruined 4 hours
;-;
f
there is no "/" in env. variable on vercel
r
It's still not querying www.finicky.pet/
which means the apiDomain set on the frontend is still finicky.pet/
f
how's that possible? I just committed to vercel, and set the env. variable to https://www.finicky.pet
they are all using process.env.NEXT_PUBLIC_HOST
which is the env variable
if you poke around the static pages there's no error, but go to the signin page it err's out
Copy code
supertokens.init(backendConfig());

export default async function superTokens(req, res) {
  // NOTE: We need CORS only if we are querying the APIs from a different origin
  await NextCors(req, res, {
    methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
    origin: process.env.NEXT_PUBLIC_HOST,
    credentials: true,
    allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],
  });

  await superTokensNextWrapper(
    async (next) => {
      await middleware()(req, res, next);
    },
    req,
    res
  );
  if (!res.writableEnded) {
    res.status(404).send("Not found");
  }
}
r
that's on your site
so please make sure it's updated correctly.
f
so it should show "https://www.finicky.pet" right?
r
yup
and same for websiteDomain
f
vercel...
Copy code
NEXT_PUBLIC_HOST

Production

VALUE

https://www.finicky.pet

Updated 14m ago



NAME
NEXT_PUBLIC_HOST
VALUE
https://www.finicky.pet
ENVIRONMENT
​
Production
​
Preview
Select Custom Branch

​
Development
maybe needs to propagate, or something?
r
no idea
maybe the version i have is cached
try rebuilding your app.
Cause the env vars for the frontend are injected into the app during building time
f
rebuilding...
ok, different error...
_app-376a5bb26884a74a.js:1          POST https://www.finicky.pet/api/auth/session/refresh 401
actually, I think we're error free
r
yup.. that's expected
f
no, can't get to signin page
redirects back to home
why so?
r
not sure
are you doing some manual redirection on the /auth route?
f
yeah, keep getting that error 401 /auth/session/refresh
um, no
r
Can you enable debug logging on the frontend and show me the output?
f
frontendConfig() ?
r
yea see the docs please
f
don't know I did it right. This is in frontendConfig()...
Copy code
return {
    enableDebugLogs: true,
    appInfo,
    recipeList: [
      EmailPasswordReact.init({
        getRedirectionURL: async (context) => {
          if (context.action === "SUCCESS") {
            if (context.redirectToPath !== undefined) {
              // navigate back to where the user was before authenticated
              return context.redirectToPath;
            }
            return "/dashboard";
          }
          return undefined;
        },
r
this is fine
f
where's the output? console?
r
it should be yae
what version of the frontend SDK are you using?
f
I just installed last week
r
which version?
f
"supertokens-auth-react": "^0.20.5", "supertokens-node": "^9.2.0",
r
upgrade supertokens-auth-react to 0.21.3
"^0.21.3"
f
ok, building on vercel
ok done
home page(statice)
This is when trying to access SignIn page...
see those?
r
You are wrapping your whole app with
EmailPasswordAuthNoSSR
?
f
yes
I'm using the development URI's is that an issue?
*URI and API Key
r
no that's not an issue
hwo is your home page being rendered? Is it wrapped around
EmailPasswordAuthNoSSR
too?
with requireAuth={false} ?
f
_app.js is wrapped, which means every page
Copy code
if (typeof window !== "undefined") {
  // we only want to call this init function on the frontend, so we check typeof window !== 'undefined'
  SuperTokensReact.init(frontendConfig());
}

const EmailPasswordAuthNoSSR = dynamic(
  new Promise((res) => res(EmailPassword.EmailPasswordAuth)),
  { ssr: false }
);

export default function App({ Component, pageProps }) {
  const securityLevel = Component.securityLevel;
  const getLayout = Component.getLayout || ((page) => page);

  if (securityLevel === "full") {
    return (
      <EmailPasswordAuthNoSSR>
        {getLayout(<Component {...pageProps} />)}
      </EmailPasswordAuthNoSSR>
    );
  } else {
    return (
      <EmailPasswordAuthNoSSR requireAuth={false}>
        {getLayout(<Component {...pageProps} />)}
      </EmailPasswordAuthNoSSR>
    );
  }
}
r
What is the value of securityLevel?
f
it's set in the pages. So a page like home page would have no security level, so does not require auth
but, the dashboard pages have this logic...
Dashboard.securityLevel = securityLevel("full");
r
hmm. Can you print something out in your home page component? Does that get printed out?
f
just show you what displays on home page?
r
i mean right now, the home page is just empty
f
yes, they are all just placeholder pages,
just shows the header, title, and footer
r
ah right.. ok. i thought there was some issue with that
f
no
if you click on the avataar an choose signin, you'll get redirected to home
that's the issue
r
can i see the code the for auth page?
f
Copy code
const SuperTokensComponentNoSSR = dynamic(
  new Promise((res) => res(SuperTokens.getRoutingComponent)),
  { ssr: false }
);

export default function Auth() {
  // if the user visits a page that is not handled by us (like /auth/random), then we redirect them back to the auth page.
  useEffect(() => {
    if (SuperTokens.canHandleRoute() === false) {
      redirectToAuth();
    }
  }, []);

  return <SuperTokensComponentNoSSR />;
}
Auth.getLayout = function getLayout(page) {
  return (
    <Layout
      pageTitle="Finicky.Pet"
      contentTitle=""
      metaDescription="Your online marketplace for buying and selling new and used pet items!"
      canonical="/"
    >
      <SingleColumnLayout>{page}</SingleColumnLayout>
    </Layout>
  );
};
that's
auth/[[...path]].js
r
Is
Layout
redirecting? Cause it has
canonical="/"
im not sure
f
no
but I'll change that and re commit
is it that
redirectToAuth()
in useEffec()?
r
Can you also remove
getRedirectionURL
and see what happens?
redirectToAuth() should navigate to /auth page..
oh right.. what is the value of appInfo.websiteBasePath?
f
that's in frontendConfig() right?
r
you wanna remove
appInfo.websiteBasePath
cause by default it is /auth
you are setting it to something else i think
f
yes ,I though you guys said to change it to process...NEXT_PUBLIC_HOST?
r
no.. websiteDomain should be that
websiteBasePath should be "/auth"
f
rebuilding, not changed redirectionURL yet
that's prolly gonna do it, makes sense
r
yup
f
yup
sweet I think we're cool, got to remove debug now
thanks again for your help
4 Views