unwilling-turquoise
unwilling-turquoise5d ago

How do you make authenticated requests using data providers on the server side in next.js?

It looks like the api calls are happening on the client side which exposes the access tokens
8 Replies
kapa.ai
kapa.ai5d ago
Hi @Harsh Maur (SaaS Alerts). I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To make authenticated requests using data providers on the server side in Next.js with refine, you should configure your data provider to include authentication tokens (such as access tokens) in the request headers on the server, rather than exposing them to the client. How to Do It 1. Store Tokens Securely on the Server:
On the server side, tokens should be stored in HTTP-only cookies or in a secure server-side session, not in localStorage or client-accessible cookies. 2. Pass Tokens in Server-Side Data Provider:
When you create your data provider instance for the server, you can inject the token into the request headers. This is typically done by reading the token from cookies or the request context in your server-side functions (e.g., getServerSideProps or server components). #### Example: Custom Fetcher with Token from Cookies Suppose you are using a GraphQL data provider. You can create a custom fetcher that reads the token from cookies (using a library like nookies or Next.js's cookies API):
import graphqlDataProvider, { GraphQLClient } from "@refinedev/nestjs-query";
import { cookies } from "next/headers";

const API_URL = "<https://your-api-url.com";>

const client = new GraphQLClient(API_URL, {
fetch: async (url: string, options: RequestInit) => {
// Read token from server-side cookies
const cookieStore = cookies();
const token = cookieStore.get("auth")?.value;

return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: token ? `Bearer ${token}` : "",
},
});
},
});

export const dataProvider = graphqlDataProvider(client);
import graphqlDataProvider, { GraphQLClient } from "@refinedev/nestjs-query";
import { cookies } from "next/headers";

const API_URL = "<https://your-api-url.com";>

const client = new GraphQLClient(API_URL, {
fetch: async (url: string, options: RequestInit) => {
// Read token from server-side cookies
const cookieStore = cookies();
const token = cookieStore.get("auth")?.value;

return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: token ? `Bearer ${token}` : "",
},
});
},
});

export const dataProvider = graphqlDataProvider(client);
This ensures the token is only available on the server and never sent to the client, keeping it secure. #### Using Providers in Both Server and Client Refine recommends splitting your providers into server and client versions. On the server, you can safely access cookies or headers to retrieve tokens, while on the client you might use a different mechanism (like js-cookie for demo purposes). See the official documentation for a full example of this pattern. #### Example Directory Structure
/src/providers/
data-provider/
data-provider.server.tsx // Reads token from cookies (server-side)
data-provider.client.tsx // Uses localStorage or js-cookie (client-side)
/src/providers/
data-provider/
data-provider.server.tsx // Reads token from cookies (server-side)
data-provider.client.tsx // Uses localStorage or js-cookie (client-side)
Key Points - Never expose access tokens to the client by putting them in localStorage or client-accessible cookies if you want to keep them secure. - Always read tokens from secure, server-only storage (like HTTP-only cookies) when making server-side requests. - Configure your data provider to inject the token into the request headers on the server. For more details and code examples, see the refine documentation on using providers in both server and client side and authentication with data providers and server-side authentication. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5d ago
<@1229671849034780702> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
unwilling-turquoise
unwilling-turquoiseOP5d ago
@kapa.ai how is localstorage not visible to clients? the users can easily see the value in the browser @kapa.ai how is localstorage not visible to clients? the users can easily see the value in the browser
kapa.ai
kapa.ai5d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- You are correct—localStorage is always visible to the client. Any data stored in localStorage can be accessed, viewed, and modified by users through their browser's developer tools. This is why localStorage is not considered secure for storing sensitive information like access tokens or authentication credentials. Refine's documentation and examples often use localStorage for simplicity and demonstration purposes, but this is not recommended for production environments where security is a concern. For secure storage of tokens, especially in Next.js applications, you should use HTTP-only cookies, which are not accessible via JavaScript on the client side and are only sent to the server with each request. This approach is highlighted in the refine documentation for server-side authentication in Next.js, where cookies (using libraries like nookies) are used to store authentication data securely and are accessed only on the server side Next.js server-side authentication. In summary:
- localStorage is visible to clients and should not be used for sensitive data. - For secure authentication, use HTTP-only cookies or other server-side storage mechanisms.
- The use of localStorage in refine examples is for demonstration and not for production security. If you need to implement secure authentication in a Next.js app with refine, follow the server-side cookie approach as shown in the documentation Next.js server-side authentication. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5d ago
<@1229671849034780702> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
unwilling-turquoise
unwilling-turquoiseOP4d ago
@kapa.ai how do I dispaly logged in user details in the uI
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To display the logged-in user details in the UI with refine, you should use the useGetIdentity hook. This hook retrieves the user information provided by your authProvider's getIdentity method. Example:
import { useGetIdentity } from "@refinedev/core";

export const User = () => {
const { data: identity } = useGetIdentity();

return <span>{identity?.fullName}</span>;
};
import { useGetIdentity } from "@refinedev/core";

export const User = () => {
const { data: identity } = useGetIdentity();

return <span>{identity?.fullName}</span>;
};
Your authProvider should implement the getIdentity method to return the user details, for example:
const authProvider = {
// ...
getIdentity: async () => {
return {
id: 1,
fullName: "Jane Doe",
};
},
// ...
};
const authProvider = {
// ...
getIdentity: async () => {
return {
id: 1,
fullName: "Jane Doe",
};
},
// ...
};
This way, you can access and display user details such as name or email anywhere in your application UI useGetIdentity documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1229671849034780702> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?