How can I check authorization in React Server Actions using NextJS?

I am using React Server Actions where I need to verify the identity of the currently authenticated user. How can I access this server side, since hooks are not available in React Server Actions and the Auth Provider seems to be client side?
2 Replies
kapa.ai
kapa.ai3w ago
Hi @Klas Jersevi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To check authorization in React Server Actions using Next.js, you can utilize the authProvider's check function on the server side. This approach allows you to verify the identity of the currently authenticated user without relying on client-side hooks. Here's a step-by-step guide on how to achieve this: 1. Define the authProvider with the check function: Ensure your authProvider includes a check function that can handle both server-side and client-side contexts. Below is an example of how you might define this in src/providers/auth-provider.ts:
import { AuthProvider } from "@refinedev/core";
import nookies from "nookies";

const COOKIE_NAME = "user";

export const authProvider: AuthProvider = {
check: async (context) => {
let user = undefined;
if (context) {
// for SSR
const cookies = nookies.get(context);
user = cookies[COOKIE_NAME];
} else {
// for CSR
const cookies = nookies.get(null);
user = cookies[COOKIE_NAME];
}

if (!user) {
return {
authenticated: false,
error: {
message: "Check failed",
name: "Unauthorized",
},
logout: true,
redirectTo: "/login",
};
}

return {
authenticated: true,
};
},
// other authProvider methods...
};

import { AuthProvider } from "@refinedev/core";
import nookies from "nookies";

const COOKIE_NAME = "user";

export const authProvider: AuthProvider = {
check: async (context) => {
let user = undefined;
if (context) {
// for SSR
const cookies = nookies.get(context);
user = cookies[COOKIE_NAME];
} else {
// for CSR
const cookies = nookies.get(null);
user = cookies[COOKIE_NAME];
}

if (!user) {
return {
authenticated: false,
error: {
message: "Check failed",
name: "Unauthorized",
},
logout: true,
redirectTo: "/login",
};
}

return {
authenticated: true,
};
},
// other authProvider methods...
};

Source (https://refine.dev/docs/routing/integrations/next-js/#server-side) 2. Use the check function in your server-side components: You can call the check function inside your server components or server-side functions like getServerSideProps. Here is an example of how to use it in a server component:
import { authProvider } from "@providers/auth-provider";
import { redirect } from "next/navigation";

export default async function IndexPage() {
const { hasAuth, data } = await getData();

if (!hasAuth) {
return redirect("/login");
}

return (
<div>
<h1>Posts</h1>
<ul>
{data?.map((post: any) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}

async function getData() {
const hasAuth = await authProvider.check();

let data = null;
if (hasAuth) {
data = await dataProvider.getList({
resource: "posts",
});
}

return {
hasAuth,
data,
};
}

import { authProvider } from "@providers/auth-provider";
import { redirect } from "next/navigation";

export default async function IndexPage() {
const { hasAuth, data } = await getData();

if (!hasAuth) {
return redirect("/login");
}

return (
<div>
<h1>Posts</h1>
<ul>
{data?.map((post: any) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}

async function getData() {
const hasAuth = await authProvider.check();

let data = null;
if (hasAuth) {
data = await dataProvider.getList({
resource: "posts",
});
}

return {
hasAuth,
data,
};
}

Source (https://refine.dev/docs/routing/integrations/next-js/#app-directory-1) 3. Protect API routes: If you need to protect API routes, you can use JWT authentication and middleware to verify tokens. Here is an example of how to implement JWT authentication in an API route: ```typescript import jwt from "jsonwebtoken";
export default function handler(req, res) {
const { method } = req;
if (method === "POST") {
const { username, password } = req.body;
// Verify user credentials
if (username === "user ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@1012464434154852352> kapa.ai is still learning and improving, please let us know how it did by reacting below