@ory/nextjs
Version:
This library was generated with [Nx](https://nx.dev).
220 lines (214 loc) • 7.09 kB
JavaScript
import { handleFlowError, FrontendApi, Configuration, FlowType } from '@ory/client-fetch';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { useSearchParams } from 'next/navigation';
import 'set-cookie-parser';
import 'cookie';
import 'psl';
// src/utils/sdk.ts
function orySdkUrl() {
let baseUrl;
if (process.env["NEXT_PUBLIC_ORY_SDK_URL"]) {
baseUrl = process.env["NEXT_PUBLIC_ORY_SDK_URL"];
}
if (!baseUrl) {
throw new Error(
"You need to set environment variable `NEXT_PUBLIC_ORY_SDK_URL` to your Ory Network SDK URL."
);
}
return baseUrl.replace(/\/$/, "");
}
function isProduction() {
return ["production", "prod"].indexOf(
process.env["VERCEL_ENV"] || process.env["NODE_ENV"] || ""
) > -1;
}
function guessPotentiallyProxiedOrySdkUrl(options) {
if (isProduction()) {
return orySdkUrl();
}
if (process.env["VERCEL_ENV"]) {
if (!isProduction() && process.env["VERCEL_URL"]) {
return `https://${process.env["VERCEL_URL"]}`.replace(/\/$/, "");
}
if (process.env["__NEXT_PRIVATE_ORIGIN"]) {
return process.env["__NEXT_PRIVATE_ORIGIN"].replace(/\/$/, "");
}
}
if (typeof window !== "undefined") {
return window.location.origin;
}
if (options?.knownProxiedUrl) {
return options.knownProxiedUrl;
}
const final = orySdkUrl();
console.warn(
`Unable to determine a suitable SDK URL for setting up the Next.js integration of Ory Elements. Will proceed using default Ory SDK URL "${final}". This is likely not what you want for local development and your authentication and login may not work.`
);
return final;
}
// src/pages/client.ts
var clientSideFrontendClient = () => new FrontendApi(
new Configuration({
headers: {
Accept: "application/json"
},
credentials: "include",
basePath: guessPotentiallyProxiedOrySdkUrl({
knownProxiedUrl: window.location.origin
})
})
);
function onValidationError(value) {
return value;
}
var toBrowserEndpointRedirect = (params, flowType) => guessPotentiallyProxiedOrySdkUrl({
knownProxiedUrl: window.location.origin
}) + "/self-service/" + flowType.toString() + "/browser?" + new URLSearchParams(params).toString();
var handleRestartFlow = (searchParams, flowType) => () => {
window.location.assign(toBrowserEndpointRedirect(searchParams, flowType));
};
function useOnRedirect() {
const router = useRouter();
return (url, external) => {
if (external) {
window.location.assign(url);
} else {
void router.push(url);
}
};
}
// src/utils/rewrite.ts
function rewriteJsonResponse(obj, proxyUrl) {
return Object.fromEntries(
Object.entries(obj).filter(([_, value]) => value !== void 0).map(([key, value]) => {
if (Array.isArray(value)) {
return [
key,
value.map((item) => {
if (typeof item === "object" && item !== null) {
return rewriteJsonResponse(item, proxyUrl);
} else if (typeof item === "string" && proxyUrl) {
return item.replaceAll(orySdkUrl(), proxyUrl);
}
return item;
}).filter((item) => item !== void 0)
];
} else if (typeof value === "object" && value !== null) {
return [key, rewriteJsonResponse(value, proxyUrl)];
} else if (typeof value === "string" && proxyUrl) {
return [key, value.replaceAll(orySdkUrl(), proxyUrl)];
}
return [key, value];
})
);
}
// src/utils/utils.ts
function toValue(res) {
return res.value().then((v) => rewriteJsonResponse(v));
}
// src/pages/flow.ts
function createUseFlowFactory(flowType, createFlow, getFlow) {
return () => {
const [flow, setFlow] = useState();
const router = useRouter();
const searchParams = useSearchParams();
const onRestartFlow = handleRestartFlow(searchParams, flowType);
const onRedirect = useOnRedirect();
const errorHandler = handleFlowError({
onValidationError,
onRestartFlow,
onRedirect
});
const handleSetFlow = async (flow2) => {
setFlow(flow2);
await router.replace({
query: { flow: flow2.id }
});
return;
};
useEffect(() => {
const id = searchParams.get("flow");
if (!router.isReady || flow !== void 0) {
return;
}
if (!id) {
createFlow(searchParams).then(toValue).then(handleSetFlow).catch(errorHandler);
return;
}
getFlow(id).then(toValue).then(handleSetFlow).catch(errorHandler);
}, [searchParams, router, router.isReady, flow]);
return flow;
};
}
var useRegistrationFlow = createUseFlowFactory(
FlowType.Registration,
(params) => {
return clientSideFrontendClient().createBrowserRegistrationFlowRaw({
returnTo: params.get("return_to") ?? void 0,
loginChallenge: params.get("registration_challenge") ?? void 0,
afterVerificationReturnTo: params.get("after_verification_return_to") ?? void 0,
organization: params.get("organization") ?? void 0
});
},
(id) => clientSideFrontendClient().getRegistrationFlowRaw({ id })
);
var useVerificationFlow = createUseFlowFactory(
FlowType.Verification,
(params) => {
return clientSideFrontendClient().createBrowserVerificationFlowRaw({
returnTo: params.get("return_to") ?? void 0
});
},
(id) => clientSideFrontendClient().getVerificationFlowRaw({ id })
);
var useRecoveryFlow = createUseFlowFactory(
FlowType.Recovery,
(params) => {
return clientSideFrontendClient().createBrowserRecoveryFlowRaw({
returnTo: params.get("return_to") ?? void 0
});
},
(id) => clientSideFrontendClient().getRecoveryFlowRaw({ id })
);
var useLoginFlow = createUseFlowFactory(
FlowType.Login,
(params) => {
return clientSideFrontendClient().createBrowserLoginFlowRaw({
refresh: params.get("refresh") === "true",
aal: params.get("aal") ?? void 0,
returnTo: params.get("return_to") ?? void 0,
cookie: params.get("cookie") ?? void 0,
loginChallenge: params.get("login_challenge") ?? void 0,
organization: params.get("organization") ?? void 0,
via: params.get("via") ?? void 0
});
},
(id) => clientSideFrontendClient().getLoginFlowRaw({ id })
);
var useSettingsFlow = createUseFlowFactory(
FlowType.Settings,
(params) => {
return clientSideFrontendClient().createBrowserSettingsFlowRaw({
returnTo: params.get("return_to") ?? void 0,
cookie: params.get("cookie") ?? void 0
});
},
(id) => clientSideFrontendClient().getSettingsFlowRaw({ id })
);
function useLogoutFlow() {
const [flow, setFlow] = useState(void 0);
const createFlow = async () => {
const flow2 = await clientSideFrontendClient().createBrowserLogoutFlow({});
setFlow(flow2);
};
useEffect(() => {
if (!flow) {
void createFlow();
}
}, []);
return flow;
}
export { useLoginFlow, useLogoutFlow, useRecoveryFlow, useRegistrationFlow, useSettingsFlow, useVerificationFlow };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map