Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

What is the best way to create a server function in solid start?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219-thinking-32k’s answer.
  1. User

    What is the best way to create a server function in solid start?

  2. Claude Assistant

    In SolidStart, you create server functions using the "use server" directive. Here's the most effective approach:

    Basic Server Function:

    "use server";
    
    export async function getUser(id) {
      // This runs only on the server
      const user = await db.user.findUnique({ where: { id } });
      return user;
    }
    

    Key patterns for server functions:

    File-based approach - Create a dedicated file (e.g., src/lib/api.js):

    "use server";
    
    export async function createPost(formData) {
      const title = formData.get("title");
      const content = formData.get("content");
      
      // Server-side validation
      if (!title || !content) {
        throw new Error("Title and content are required");
      }
      
      const post = await db.post.create({
        data: { title, content }
      });
      
      return post;
    }
    

    Inline server functions within components:

    import { createSignal } from "solid-js";
    
    export default function UserProfile() {
      const [user, setUser] = createSignal();
      
      const fetchUser = async (id) => {
        "use server";
        return await db.user.findUnique({ where: { id } });
      };
      
      return (
        <div>
          <button onClick={() => fetchUser(1).then(setUser)}>
            Load User
          </button>
          {user() && <p>{user().name}</p>}
        </div>
      );
    }
    

    Best practices:

    • Always validate inputs on the server side
    • Handle errors appropriately with try-catch blocks
    • Use TypeScript for better type safety across client-server boundaries
    • Keep server functions focused and single-purpose
    • Consider using cache from @solidjs/router for data that should be cached

    Server functions automatically handle serialization between client and server, making them much simpler than traditional API routes for most use cases.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.