@descope/nextjs-sdk 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/cjs/server/authMiddleware.js +12 -5
- package/dist/cjs/server/authMiddleware.js.map +1 -1
- package/dist/cjs/server/constants.js +1 -1
- package/dist/cjs/shared/constants.js +1 -1
- package/dist/esm/server/authMiddleware.js +12 -5
- package/dist/esm/server/authMiddleware.js.map +1 -1
- package/dist/esm/server/constants.js +1 -1
- package/dist/esm/shared/constants.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -149,7 +149,8 @@ export default authMiddleware({
|
|
|
149
149
|
// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2
|
|
150
150
|
redirectUrl?: string,
|
|
151
151
|
|
|
152
|
-
// These are the public and private routes in your app.
|
|
152
|
+
// These are the public and private routes in your app. You can also use wildcards (e.g. /api/*) with routes as well in these definitions.
|
|
153
|
+
// Read more about how to use these below.
|
|
153
154
|
publicRoutes?: string[],
|
|
154
155
|
privateRoutes?: string[]
|
|
155
156
|
// If you having privateRoutes and publicRoutes defined at the same time, privateRoutes will be ignored.
|
|
@@ -18,19 +18,26 @@ const getSessionJwt = (req) => {
|
|
|
18
18
|
}
|
|
19
19
|
return undefined;
|
|
20
20
|
};
|
|
21
|
+
const matchWildcardRoute = (route, path) => {
|
|
22
|
+
let regexPattern = route.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
|
|
23
|
+
// Convert wildcard (*) to match path segments only
|
|
24
|
+
regexPattern = regexPattern.replace(/\*/g, '[^/]*');
|
|
25
|
+
const regex = new RegExp(`^${regexPattern}$`);
|
|
26
|
+
return regex.test(path);
|
|
27
|
+
};
|
|
21
28
|
const isPublicRoute = (req, options) => {
|
|
22
29
|
// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined
|
|
23
|
-
const publicRoutes =
|
|
24
|
-
const
|
|
25
|
-
const isDefaultPublicRoute = Object.values(constants.DEFAULT_PUBLIC_ROUTES).includes(
|
|
30
|
+
const { publicRoutes = [], privateRoutes = [] } = options;
|
|
31
|
+
const { pathname } = req.nextUrl;
|
|
32
|
+
const isDefaultPublicRoute = Object.values(constants.DEFAULT_PUBLIC_ROUTES).includes(pathname);
|
|
26
33
|
if (publicRoutes.length > 0) {
|
|
27
34
|
if (privateRoutes.length > 0) {
|
|
28
35
|
console.warn('Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.');
|
|
29
36
|
}
|
|
30
|
-
return isDefaultPublicRoute || publicRoutes.
|
|
37
|
+
return isDefaultPublicRoute || publicRoutes.some((route) => matchWildcardRoute(route, pathname));
|
|
31
38
|
}
|
|
32
39
|
if (privateRoutes.length > 0) {
|
|
33
|
-
return (isDefaultPublicRoute || !privateRoutes.
|
|
40
|
+
return (isDefaultPublicRoute || !privateRoutes.some((route) => matchWildcardRoute(route, pathname)));
|
|
34
41
|
}
|
|
35
42
|
// If no routes are provided, all routes are private
|
|
36
43
|
return isDefaultPublicRoute;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport type { AuthenticationInfo } from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n};\n\nconst getSessionJwt = (req: NextRequest): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(descopeSdk.SessionTokenCookieName)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst publicRoutes =
|
|
1
|
+
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport type { AuthenticationInfo } from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n};\n\nconst getSessionJwt = (req: NextRequest): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(descopeSdk.SessionTokenCookieName)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst matchWildcardRoute = (route: string, path: string) => {\n\tlet regexPattern = route.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n \n\t// Convert wildcard (*) to match path segments only\n\tregexPattern = regexPattern.replace(/\\*/g, '[^/]*');\n\tconst regex = new RegExp(`^${regexPattern}$`);\n \n\treturn regex.test(path);\n };\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst { publicRoutes = [], privateRoutes = [] } = options;\n\tconst { pathname } = req.nextUrl;\n\n\tconst isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(\n\t\tpathname\n\t);\n\n\tif (publicRoutes.length > 0) {\n\t\tif (privateRoutes.length > 0) {\n\t\t\tconsole.warn(\n\t\t\t\t'Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.'\n\t\t\t);\n\t\t}\n\t\treturn isDefaultPublicRoute || publicRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t}\n\n\tif (privateRoutes.length > 0) {\n\t\treturn (\n\t\t\tisDefaultPublicRoute || !privateRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\t// If no routes are provided, all routes are private\n\treturn isDefaultPublicRoute;\n};\n\nconst addSessionToHeadersIfExists = (\n\theaders: Headers,\n\tsession: AuthenticationInfo | undefined\n): Headers => {\n\tif (session) {\n\t\tconst requestHeaders = new Headers(headers);\n\t\trequestHeaders.set(\n\t\t\tDESCOPE_SESSION_HEADER,\n\t\t\tBuffer.from(JSON.stringify(session)).toString('base64')\n\t\t);\n\t\treturn requestHeaders;\n\t}\n\treturn headers;\n};\n\n// returns a Middleware that checks if the user is authenticated\n// if the user is not authenticated, it redirects to the redirectUrl\n// if the user is authenticated, it adds the session to the headers\nconst createAuthMiddleware =\n\t(options: MiddlewareOptions = {}) =>\n\tasync (req: NextRequest) => {\n\t\tconsole.debug('Auth middleware starts');\n\n\t\tconst jwt = getSessionJwt(req);\n\n\t\t// check if the user is authenticated\n\t\tlet session: AuthenticationInfo | undefined;\n\t\ttry {\n\t\t\tsession = await getGlobalSdk({\n\t\t\t\tprojectId: options.projectId,\n\t\t\t\tbaseUrl: options.baseUrl\n\t\t\t}).validateJwt(jwt);\n\t\t} catch (err) {\n\t\t\tconsole.debug('Auth middleware, Failed to validate JWT', err);\n\t\t\tif (!isPublicRoute(req, options)) {\n\t\t\t\tconst redirectUrl = options.redirectUrl || DEFAULT_PUBLIC_ROUTES.signIn;\n\t\t\t\tconst url = req.nextUrl.clone();\n\t\t\t\t// Create a URL object for redirectUrl. 'http://example.com' is just a placeholder.\n\t\t\t\tconst parsedRedirectUrl = new URL(redirectUrl, 'http://example.com');\n\t\t\t\turl.pathname = parsedRedirectUrl.pathname;\n\n\t\t\t\tconst searchParams = mergeSearchParams(\n\t\t\t\t\turl.search,\n\t\t\t\t\tparsedRedirectUrl.search\n\t\t\t\t);\n\t\t\t\tif (searchParams) {\n\t\t\t\t\turl.search = searchParams;\n\t\t\t\t}\n\t\t\t\tconsole.debug(`Auth middleware, Redirecting to ${redirectUrl}`);\n\t\t\t\treturn NextResponse.redirect(url);\n\t\t\t}\n\t\t}\n\n\t\tconsole.debug('Auth middleware finishes');\n\t\t// add the session to the request, if it exists\n\t\tconst headers = addSessionToHeadersIfExists(req.headers, session);\n\t\treturn NextResponse.next({\n\t\t\trequest: {\n\t\t\t\theaders\n\t\t\t}\n\t\t});\n\t};\n\nexport default createAuthMiddleware;\n"],"names":["DEFAULT_PUBLIC_ROUTES","DESCOPE_SESSION_HEADER","getGlobalSdk","mergeSearchParams","NextResponse"],"mappings":";;;;;;;;AAAA;AAiCA,MAAM,aAAa,GAAG,CAAC,GAAgB,KAAwB;AAC9D,IAAA,IAAI,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3D,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AAED,IAAA,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,UAAU,CAAC,sBAAsB,CAAC,EAAE,KAAK,CAAC;IACjE,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AACD,IAAA,OAAO,SAAS,CAAC;AAClB,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,KAAa,EAAE,IAAY,KAAI;IAC1D,IAAI,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;;IAG/D,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,CAAI,CAAA,EAAA,YAAY,CAAG,CAAA,CAAA,CAAC,CAAC;AAE9C,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACvB,CAAC,CAAC;AA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,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;;IAE1C,MAAM,OAAO,GAAG,2BAA2B,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,OAAOA,sBAAY,CAAC,IAAI,CAAC;AACxB,QAAA,OAAO,EAAE;YACR,OAAO;AACP,SAAA;AACD,KAAA,CAAC,CAAC;AACJ;;;;"}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
const DESCOPE_SESSION_HEADER = 'x-descope-session';
|
|
4
4
|
const baseHeaders = {
|
|
5
5
|
'x-descope-sdk-name': 'nextjs',
|
|
6
|
-
'x-descope-sdk-version': "0.
|
|
6
|
+
'x-descope-sdk-version': "0.7.1"
|
|
7
7
|
};
|
|
8
8
|
const DEFAULT_PUBLIC_ROUTES = {
|
|
9
9
|
signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
|
|
@@ -16,19 +16,26 @@ const getSessionJwt = (req) => {
|
|
|
16
16
|
}
|
|
17
17
|
return undefined;
|
|
18
18
|
};
|
|
19
|
+
const matchWildcardRoute = (route, path) => {
|
|
20
|
+
let regexPattern = route.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
|
|
21
|
+
// Convert wildcard (*) to match path segments only
|
|
22
|
+
regexPattern = regexPattern.replace(/\*/g, '[^/]*');
|
|
23
|
+
const regex = new RegExp(`^${regexPattern}$`);
|
|
24
|
+
return regex.test(path);
|
|
25
|
+
};
|
|
19
26
|
const isPublicRoute = (req, options) => {
|
|
20
27
|
// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined
|
|
21
|
-
const publicRoutes =
|
|
22
|
-
const
|
|
23
|
-
const isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(
|
|
28
|
+
const { publicRoutes = [], privateRoutes = [] } = options;
|
|
29
|
+
const { pathname } = req.nextUrl;
|
|
30
|
+
const isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(pathname);
|
|
24
31
|
if (publicRoutes.length > 0) {
|
|
25
32
|
if (privateRoutes.length > 0) {
|
|
26
33
|
console.warn('Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.');
|
|
27
34
|
}
|
|
28
|
-
return isDefaultPublicRoute || publicRoutes.
|
|
35
|
+
return isDefaultPublicRoute || publicRoutes.some((route) => matchWildcardRoute(route, pathname));
|
|
29
36
|
}
|
|
30
37
|
if (privateRoutes.length > 0) {
|
|
31
|
-
return (isDefaultPublicRoute || !privateRoutes.
|
|
38
|
+
return (isDefaultPublicRoute || !privateRoutes.some((route) => matchWildcardRoute(route, pathname)));
|
|
32
39
|
}
|
|
33
40
|
// If no routes are provided, all routes are private
|
|
34
41
|
return isDefaultPublicRoute;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport type { AuthenticationInfo } from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n};\n\nconst getSessionJwt = (req: NextRequest): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(descopeSdk.SessionTokenCookieName)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst publicRoutes =
|
|
1
|
+
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport type { AuthenticationInfo } from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n};\n\nconst getSessionJwt = (req: NextRequest): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(descopeSdk.SessionTokenCookieName)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst matchWildcardRoute = (route: string, path: string) => {\n\tlet regexPattern = route.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n \n\t// Convert wildcard (*) to match path segments only\n\tregexPattern = regexPattern.replace(/\\*/g, '[^/]*');\n\tconst regex = new RegExp(`^${regexPattern}$`);\n \n\treturn regex.test(path);\n };\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst { publicRoutes = [], privateRoutes = [] } = options;\n\tconst { pathname } = req.nextUrl;\n\n\tconst isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(\n\t\tpathname\n\t);\n\n\tif (publicRoutes.length > 0) {\n\t\tif (privateRoutes.length > 0) {\n\t\t\tconsole.warn(\n\t\t\t\t'Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.'\n\t\t\t);\n\t\t}\n\t\treturn isDefaultPublicRoute || publicRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t}\n\n\tif (privateRoutes.length > 0) {\n\t\treturn (\n\t\t\tisDefaultPublicRoute || !privateRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\t// If no routes are provided, all routes are private\n\treturn isDefaultPublicRoute;\n};\n\nconst addSessionToHeadersIfExists = (\n\theaders: Headers,\n\tsession: AuthenticationInfo | undefined\n): Headers => {\n\tif (session) {\n\t\tconst requestHeaders = new Headers(headers);\n\t\trequestHeaders.set(\n\t\t\tDESCOPE_SESSION_HEADER,\n\t\t\tBuffer.from(JSON.stringify(session)).toString('base64')\n\t\t);\n\t\treturn requestHeaders;\n\t}\n\treturn headers;\n};\n\n// returns a Middleware that checks if the user is authenticated\n// if the user is not authenticated, it redirects to the redirectUrl\n// if the user is authenticated, it adds the session to the headers\nconst createAuthMiddleware =\n\t(options: MiddlewareOptions = {}) =>\n\tasync (req: NextRequest) => {\n\t\tconsole.debug('Auth middleware starts');\n\n\t\tconst jwt = getSessionJwt(req);\n\n\t\t// check if the user is authenticated\n\t\tlet session: AuthenticationInfo | undefined;\n\t\ttry {\n\t\t\tsession = await getGlobalSdk({\n\t\t\t\tprojectId: options.projectId,\n\t\t\t\tbaseUrl: options.baseUrl\n\t\t\t}).validateJwt(jwt);\n\t\t} catch (err) {\n\t\t\tconsole.debug('Auth middleware, Failed to validate JWT', err);\n\t\t\tif (!isPublicRoute(req, options)) {\n\t\t\t\tconst redirectUrl = options.redirectUrl || DEFAULT_PUBLIC_ROUTES.signIn;\n\t\t\t\tconst url = req.nextUrl.clone();\n\t\t\t\t// Create a URL object for redirectUrl. 'http://example.com' is just a placeholder.\n\t\t\t\tconst parsedRedirectUrl = new URL(redirectUrl, 'http://example.com');\n\t\t\t\turl.pathname = parsedRedirectUrl.pathname;\n\n\t\t\t\tconst searchParams = mergeSearchParams(\n\t\t\t\t\turl.search,\n\t\t\t\t\tparsedRedirectUrl.search\n\t\t\t\t);\n\t\t\t\tif (searchParams) {\n\t\t\t\t\turl.search = searchParams;\n\t\t\t\t}\n\t\t\t\tconsole.debug(`Auth middleware, Redirecting to ${redirectUrl}`);\n\t\t\t\treturn NextResponse.redirect(url);\n\t\t\t}\n\t\t}\n\n\t\tconsole.debug('Auth middleware finishes');\n\t\t// add the session to the request, if it exists\n\t\tconst headers = addSessionToHeadersIfExists(req.headers, session);\n\t\treturn NextResponse.next({\n\t\t\trequest: {\n\t\t\t\theaders\n\t\t\t}\n\t\t});\n\t};\n\nexport default createAuthMiddle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'nextjs',
|
|
4
|
-
'x-descope-sdk-version': "0.
|
|
4
|
+
'x-descope-sdk-version': "0.7.1"
|
|
5
5
|
};
|
|
6
6
|
const DEFAULT_PUBLIC_ROUTES = {
|
|
7
7
|
signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@descope/nextjs-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Descope NextJS SDK",
|
|
5
5
|
"author": "Descope Team <info@descope.com>",
|
|
6
6
|
"homepage": "https://github.com/descope/descope-js",
|
|
@@ -64,9 +64,9 @@
|
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@descope/node-sdk": "1.6.13",
|
|
67
|
-
"@descope/react-sdk": "2.7.
|
|
67
|
+
"@descope/react-sdk": "2.7.2",
|
|
68
68
|
"@descope/core-js-sdk": "2.36.0",
|
|
69
|
-
"@descope/web-component": "3.
|
|
69
|
+
"@descope/web-component": "3.37.0"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@babel/core": "7.26.0",
|