Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
@descope/nextjs-sdk
Advanced tools
The Descope SDK for NextJS provides convenient access to the Descope for an application written on top of NextJS. You can read more on the Descope Website.
This SDK uses under the hood the Descope React SDK and Descope Node SDK Refer to the Descope React SDK and Descope Node SDK for more details.
Project ID
is required for using the SDK. Find it on the project page in the Descope Console.Install the package with:
npm i --save @descope/nextjs-sdk
This section contains guides for App router and Pages router. For Pages router, see the Pages Router section.
// src/app/layout.tsx
import { AuthProvider } from '@descope/nextjs-sdk';
export default function RootLayout({
children
}: {
children: React.ReactNode
}) {
return (
<AuthProvider projectId="your-descope-project-id">
<html lang="en">
<body>{children}</body>
</html>
</AuthProvider>
);
}
Note: AuthProvider
uses sessionTokenViaCookie
by default, in order that the AuthMiddleware will work out of the box.
You can use default flows or provide flow id directly to the Descope component
// Login page, e.g. src/app/sign-in.tsx
import { Descope } from '@descope/nextjs-sdk';
// you can choose flow to run from the following without `flowId` instead
// import { SignInFlow, SignUpFlow, SignUpOrInFlow } from '@descope/nextjs-sdk'
const Page = () => {
return (
<Descope
flowId="sign-up-or-in"
onSuccess={(e) => console.log('Logged in!')}
onError={(e) => console.log('Could not logged in!')}
redirectAfterSuccess="/"
// redirectAfterError="/error-page"
/>
);
};
Refer to the Descope React SDK Section for a list of available props.
Note: Descope is a client component. if the component that renders it is a server component, you cannot pass onSuccess
/onError
/errorTransformer
/logger
props because they are not serializable. To redirect the user after the flow is completed, use the redirectAfterSuccess
and redirectAfterError
props.
Use the useDescope
, useSession
and useUser
hooks in your components in order to get authentication state, user details and utilities
This can be helpful to implement application-specific logic. Examples:
Note: these hooks should be used in a client component only (For example, component with use client
notation).
'use client';
import { useDescope, useSession, useUser } from '@descope/nextjs-sdk/client';
import { useCallback } from 'react';
const App = () => {
// NOTE - `useDescope`, `useSession`, `useUser` should be used inside `AuthProvider` context,
// and will throw an exception if this requirement is not met
// useSession retrieves authentication state, session loading status, and session token
const { isAuthenticated, isSessionLoading, sessionToken } = useSession();
// useUser retrieves the logged in user information
const { user } = useUser();
// useDescope retrieves Descope SDK for further operations related to authentication
// such as logout
const sdk = useDescope();
if (isSessionLoading || isUserLoading) {
return <p>Loading...</p>;
}
const handleLogout = useCallback(() => {
sdk.logout();
}, [sdk]);
if (isAuthenticated) {
return (
<>
<p>Hello {user.name}</p>
<button onClick={handleLogout}>Logout</button>
</>
);
}
return <p>You are not logged in</p>;
};
You can use NextJS Middleware to require authentication for a page/route or a group of pages/routes.
Descope SDK provides a middleware function that can be used to require authentication for a page/route or a group of pages/routes.
// src/middleware.ts
import { authMiddleware } from '@descope/nextjs-sdk/server'
export default authMiddleware({
// The Descope project ID to use for authentication
// Defaults to process.env.DESCOPE_PROJECT_ID
projectId: 'your-descope-project-id'
// The URL to redirect to if the user is not authenticated
// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided
redirectUrl?: string
// An array of public routes that do not require authentication
// In addition to the default public routes:
// - process.env.SIGN_IN_ROUTE or /sign-in if not provided
// - process.env.SIGN_UP_ROUTE or /sign-up if not provided
publicRoutes?: string[]
})
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
}
use the session()
helper to read session information in Server Components and Route handlers.
Note: session()
requires the authMiddleware
to be used for the Server Component or Route handler that uses it.
Server Component:
// src/app/page.tsx
import { session } from '@descope/nextjs-sdk/server';
async function Page() {
const sessionRes = session();
if (!sessionRes) {
// ...
}
// Use the session jwt or parsed token
const { jwt, token } = sessionRes;
}
Route handler:
// src/pages/api/routes.ts
export async function GET() {
const currSession = session();
if (!currSession.isAuthenticated) {
// ...
}
// Use the session jwt or parsed token
const { jwt, token } = currSession;
}
Use createSdk
function to create Descope SDK in server side.
Refer to the Descope Node SDK for a list of available functions.
Usage example in Route handler:
// src/pages/api/routes.ts
import { createSdk } from '@descope/nextjs-sdk/server';
const sdk = createSdk({
// The Descope project ID to use for authentication
// Defaults to process.env.DESCOPE_PROJECT_ID
projectId: 'your-descope-project-id',
// The Descope management key to use for management operations
// Defaults to process.env.DESCOPE_MANAGEMENT_KEY
managementKey: 'your-descope-management-key'
});
export async function GET(req) {
const { searchParams } = new URL(req.url);
const loginId = searchParams.get('loginId');
const { ok, data: user } = await sdk.management.user.load(loginId);
if (!ok) {
// ...
}
// Use the user data ...
}
This section is Working in progress :-) In the meantime, you can see the example in the Pages Router folder.
You can find an example react app in the examples folder. - App Router - Pages Router
To learn more please see the Descope Documentation and API reference page.
If you need help you can email Descope Support
The Descope SDK for React is licensed for use under the terms and conditions of the MIT license Agreement.
FAQs
Descope NextJS SDK
The npm package @descope/nextjs-sdk receives a total of 4,808 weekly downloads. As such, @descope/nextjs-sdk popularity was classified as popular.
We found that @descope/nextjs-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.