Overview
This article explains how to implement an authentication middleware and use it to protect access to Server Functions.
While this guide uses Better Auth as an example, the same approach can be applied to other authentication services.
What You’ll Learn
- The basics of TanStack Start Server Functions and middleware
- How to implement authentication middleware integrated with Better Auth
- A pattern for handling user sessions in a type-safe way
What Are Server Functions?
Server Functions are functions guaranteed to run on the server side. In TanStack Start, you can use Server Functions instead of REST APIs or GraphQL to exchange data between the client and server.
https://tanstack.com/start/latest/docs/framework/react/guide/server-functions
import { createServerFn } from '@tanstack/react-start'
export const getServerTime = createServerFn().handler(async () => {
// Guaranteed to run on the server
return new Date().toISOString()
})
// Can be called from anywhere
const time = await getServerTime()
What Is Middleware?
Middleware is a function that runs before a Server Function’s main handler. By using middleware, you can add cross-cutting concerns to Server Functions, such as authentication, logging, or error handling.
The authentication middleware introduced in this article checks whether a user is authenticated before allowing access to a specific Server Function.
https://tanstack.com/start/latest/docs/framework/react/guide/middleware
Benefits of Using Authentication Middleware
Using authentication middleware provides the following benefits:
- Protect Server Functions and prevent access from unauthenticated users
- Handle authenticated user information in a type-safe way within Server Functions
- Improve maintainability through reusable authentication logic, making the codebase easier to change
Prerequisites
You must have completed the Better Auth setup by following the official documentation.
https://www.better-auth.com/docs/installation
https://www.better-auth.com/docs/integrations/tanstack
Steps
1. Implement getUserSession, a function that returns the authenticated user’s session
import { createServerFn } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";
import { auth } from "@/lib/auth";
export const getUserSession = createServerFn({ method: "GET" }).handler(
async () => {
const request = getRequest();
if (!request?.headers) {
return null;
}
const userSession = await auth.api.getSession({ headers: request.headers });
if (!userSession) return null;
return { user: userSession.user, session: userSession.session };
}
);
2. Implement authMiddleware, an authentication middleware
import { redirect } from "@tanstack/react-router";
import { createMiddleware } from "@tanstack/react-start";
import { getUserSession } from "@/services/auth/server-functions";
export const authMiddleware = createMiddleware({ type: "function" }).server(
async ({ next }) => {
const userSession = await getUserSession();
if (!userSession) {
throw redirect({ to: "/" }); // Redirect to home if not authenticated
}
return next({ context: { userSession } });
}
);
The key point here is returning userSession via the next function. This enables the Server Function handler to access the user session information.
3. Implement a Server Function using the authentication middleware
import { createServerFn } from "@tanstack/react-start";
import { authMiddleware } from "@/middlewares/auth";
import { todoRepository } from "@/services/todos/repository";
export const getTodos = createServerFn()
.middleware([authMiddleware])
.handler(async ({ context }) => {
const { userSession } = context; // Type-safe access to session info
const todoList = await todoRepository.get(userSession.user.id);
return todoList;
});
Summary
This article explained how to implement authentication middleware in TanStack Start and use it to protect access to Server Functions. By using authentication middleware, you can strengthen security and handle user information in a type-safe manner. While this guide used Better Auth as an example, the same approach can be applied to other authentication services.
Top comments (0)