Sign users in to a Next.js application
This guide explains how to add Casdoor sign-in to a Next.js application and how to keep signed-out users away from protected routes.
Learning outcomes
- Initialize casdoor-js-sdk in a Next.js application.
- Send users to the Casdoor sign-in page and handle the callback.
- Protect routes with Next.js middleware.
What you need
- A running Casdoor instance. See Install the Casdoor server.
- An application in Casdoor
- A Next.js application
Sample code
Configure the SDK
-
Install casdoor-js-sdk:
npm install casdoor-js-sdk
# or: yarn add casdoor-js-sdk -
Define the configuration of the SDK. All settings are strings and all are required.
Parámetro Requerido Descripción serverUrl Sí Casdoor server URL (e.g. http://localhost:8000).clientId Sí ID del cliente de la aplicación. clientSecret Sí Secreto del cliente de la aplicación. organizationName Sí Organization name. appName Sí Nombre de la aplicación. redirectPath Sí Callback path (e.g. /callback).const sdkConfig = {
serverUrl: "https://door.casdoor.com",
clientId: "294b09fbc17f95daf2fe",
clientSecret: "dd8982f7046ccba1bbd7851d5c1ece4e52bf039d",
organizationName: "casbin",
appName: "app-vue-python-example",
redirectPath: "/callback",
};Replace
serverUrl,clientId, andclientSecretwith the values of your own Casdoor instance and application. -
In the Casdoor admin console, add the callback URL of your application, for example
http://localhost:8080/callback, to the Redirect URLs of the application.
Sign the user in
-
Send the user to the Casdoor sign-in page:
const CasdoorSDK = new Sdk(sdkConfig);
CasdoorSDK.signin_redirect(); -
After the user signs in, Casdoor redirects to
redirectPathwith an authorization code. On that page, exchange the code for an access token, read the user, and store the user in a cookie:CasdoorSDK.exchangeForAccessToken()
.then((res) => {
if (res && res.access_token) {
return CasdoorSDK.getUserInfo(res.access_token);
}
})
.then((res) => {
Cookies.set("casdoorUser", JSON.stringify(res));
});
For the other functions of the SDK, see Sign users in with a Casdoor SDK.
Protect routes with middleware
Next.js middleware runs before a request completes and can redirect it.
-
Create
middleware.tsormiddleware.jsat the root of the project: at the same level aspagesorapp, or insidesrc. -
List the protected routes and check each request against the list:
const protectedRoutes = ["/profile"];
export default function middleware(req) {
if (protectedRoutes.includes(req.nextUrl.pathname)) {
return NextResponse.redirect(new URL("/login", req.url));
}
} -
Treat a request with the
casdoorUsercookie as signed in, and redirect all other requests away from the protected routes:const protectedRoutes = ["/profile"];
const casdoorUserCookie = req.cookies.get("casdoorUser");
const isAuthenticated = !!casdoorUserCookie;
if (!isAuthenticated && protectedRoutes.includes(req.nextUrl.pathname)) {
return NextResponse.redirect(new URL("/login", req.url));
}