router icon indicating copy to clipboard operation
router copied to clipboard

server-only Module Causes Build Failure in Development Mode (Inconsistent Behavior Between Development and Production Builds)

Open jadedevin13 opened this issue 1 year ago • 0 comments

Describe the bug

The project encounters a build failure in development mode when attempting to import the server-only module from a file meant to handle server-side logic. This issue does not occur in the production build, leading to inconsistent behavior between development and production environments.

Your Example Website or App

N/A

Steps to Reproduce the Bug or Issue

In start-basic-rsc sample.

In app/utils/posts.tsx put the following

// import { notFound } from '@tanstack/react-router'
// import { createServerFn } from '@tanstack/start'
import axios from 'redaxios'
import { getPost } from './static-post'
import { createServerFn } from '@tanstack/start'

export type PostType = {
  id: string
  title: string
  body: string
}

export const fetchPost = async (postId: string) => {
  'use server'
  console.info(`Fetching post with id ${postId}...`)
  await new Promise((r) => setTimeout(r, 500))
  const post = await axios
    .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    .then((r) => r.data)
    .catch((err) => {
      if (err.status === 404) {
        // throw notFound()
      }
      throw err
    })

  return post
}

export const fetchPosts = async () => {
  'use server'
  console.info('Fetching posts...')
  await new Promise((r) => setTimeout(r, 500))
  return getServerPost()
}

export const getServerPost = createServerFn('GET', () => {
  return getPost()
})

Then add a new file static-post.ts in the same folder with the following contents.

import 'server-only'

export function getPost() {
  return [
    {
      userId: 1,
      id: 1,
      title:
        'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
      body: 'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto',
    },
  ]
}

If you try to build the project and start it. It will work fine and will not include the server only files, but in dev it will fail

2:43:47 [vite] Error when evaluating SSR module /app/utils/posts.tsx: failed to import "server-only"
|- Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.

Expected behavior

The project should build and start successfully in both development and production modes without encountering import errors.

Screenshots or Videos

No response

Platform

  • OS: macOS
  • Browser: N/A
  • Version: 1.45.2

Additional context

No response

jadedevin13 avatar Jul 15 '24 20:07 jadedevin13