09:41:00

Architecting Scalable Frontend Applications with Feature-Sliced Design (FSD)

How Feature-Sliced Design establishes strict unidirectional boundaries, prevents spaghetti imports, and scales enterprise React and Next.js teams.

Published
Reading time
8 min read
  • architecture
  • react
  • fsd
On this page

As frontend web codebases grow in complexity—surpassing hundreds of components, custom hooks, global stores, and API clients—the traditional folder structure organized by file types (components/, hooks/, utils/, services/) collapses under its own weight.

Engineers spend valuable time hunting down where specific domain logic lives. Subtle circular dependency cycles creep into imports, and refactoring a single business requirement risks breaking unrelated features across the system.

Feature-Sliced Design (FSD) solves this by introducing an architectural framework grounded in explicit layer hierarchies, high cohesion, and low coupling.


The Hierarchy of FSD Layers

Under Feature-Sliced Design, code is partitioned into standardized layers ordered from highest abstraction to lowest abstraction.

A fundamental rule governs this architecture: A module in a given layer may only import from layers strictly below it, never from layers above or sideways within the same layer.

text
┌─────────────────────────────────────────────────────────┐
│  1. App       (Providers, global router, global styles) │
├─────────────────────────────────────────────────────────┤
│  2. Pages     (Full route views composed of widgets)    │
├─────────────────────────────────────────────────────────┤
│  3. Widgets   (Self-contained composite UI sections)    │
├─────────────────────────────────────────────────────────┤
│  4. Features  (User interactions delivering value)      │
├─────────────────────────────────────────────────────────┤
│  5. Entities  (Business domain models, types, stores)   │
├─────────────────────────────────────────────────────────┤
│  6. Shared    (UI atoms, Axios client, helper utils)    │
└─────────────────────────────────────────────────────────┘

Practical Example: Implementing a Domain Slice

Let's examine how a slice within the entities layer is constructed with a dedicated public API (index.ts), strict Zustand state management, and an isolated Axios API service.

Notice how the store manages loading indicators cleanly, keeping UI components purely declarative:

typescript
/**
 * src/entities/user-profile/api/userProfileService.ts
 */
import { apiClient } from '@/shared/api/apiClient'
import type { ApiResponse } from '@/shared/api/http'
import type { UserProfile } from '../model/userProfile.types'

export const userProfileService = {
  getProfileById: async (userIdentifier: string): Promise<UserProfile> => {
    const { data: apiResponse } = await apiClient.get<ApiResponse<UserProfile>>(
      `/users/${userIdentifier}/profile`,
    )

    return apiResponse.data
  },

  updatePreferences: async (
    userIdentifier: string,
    updatedPreferences: Record<string, boolean>,
  ): Promise<UserProfile> => {
    const { data: apiResponse } = await apiClient.patch<ApiResponse<UserProfile>>(
      `/users/${userIdentifier}/preferences`,
      { preferences: updatedPreferences },
    )

    return apiResponse.data
  },
}
typescript
/**
 * src/entities/user-profile/model/userProfileStore.ts
 */
import { create } from 'zustand'
import { userProfileService } from '../api/userProfileService'
import type { UserProfile } from './userProfile.types'

interface UserProfileState {
  currentProfile: UserProfile | null
  isFetchingProfile: boolean
  profileErrorMessage: string | null
  loadUserProfile: (userIdentifier: string) => Promise<void>
}

export const useUserProfileStore = create<UserProfileState>((set) => ({
  currentProfile: null,
  isFetchingProfile: false,
  profileErrorMessage: null,

  loadUserProfile: async (userIdentifier: string) => {
    set({ isFetchingProfile: true, profileErrorMessage: null })

    try {
      const resolvedProfile = await userProfileService.getProfileById(userIdentifier)
      set({ currentProfile: resolvedProfile })
    } catch (caughtError) {
      set({
        profileErrorMessage:
          caughtError instanceof Error ? caughtError.message : 'Failed to retrieve profile data.',
      })
    } finally {
      set({ isFetchingProfile: false })
    }
  },
}))

Consuming in Widgets via Public API

Every slice exposes a single index.ts file acting as an explicit boundary. Internal subfolders (api/, model/, ui/) are never accessed directly from outside the slice.

When composing a widget, developers destructure the required state and actions cleanly without selector duplication:

tsx
/**
 * src/widgets/profile-card/ui/ProfileSummaryCard.astro (or .tsx)
 */
import { useEffect } from 'react'
import { useUserProfileStore } from '@/entities/user-profile'
import { Button } from '@/shared/ui/button'

interface ProfileSummaryCardProps {
  userIdentifier: string
}

export const ProfileSummaryCard = ({ userIdentifier }: ProfileSummaryCardProps) => {
  const { currentProfile, isFetchingProfile, profileErrorMessage, loadUserProfile } =
    useUserProfileStore()

  useEffect(() => {
    loadUserProfile(userIdentifier)
  }, [userIdentifier, loadUserProfile])

  if (isFetchingProfile) {
    return (
      <div className="flex h-48 w-full items-center justify-center rounded-2xl border border-neutral-800 bg-neutral-950">
        <span className="text-sm text-neutral-400">Loading user profile...</span>
      </div>
    )
  }

  if (profileErrorMessage) {
    return (
      <div className="rounded-2xl border border-red-500/20 bg-red-950/30 p-6 text-sm text-red-300">
        {profileErrorMessage}
      </div>
    )
  }

  return (
    <section className="flex flex-col gap-4 rounded-2xl border border-neutral-800 bg-neutral-950 p-6">
      <div className="flex items-center gap-4">
        <img
          src={currentProfile?.avatarUrl || '/photo.webp'}
          alt={currentProfile?.fullName || 'User Avatar'}
          className="size-14 rounded-full border border-neutral-700 object-cover"
        />
        <div className="flex flex-col">
          <h2 className="text-lg font-bold text-white">{currentProfile?.fullName}</h2>
          <span className="text-xs text-neutral-400">{currentProfile?.jobTitle}</span>
        </div>
      </div>

      <Button variant="outline" className="mt-2 w-full">
        Edit Preferences
      </Button>
    </section>
  )
}

Core Guidelines for FSD Mastery

  • Enforce Single-Direction Imports: Run ESLint boundary rules (eslint-plugin-boundaries) in CI pipelines to catch illegal horizontal or reverse imports before code merges.
  • Never Import from Siblings: If feature/like-article needs functionality from feature/bookmark-article, lift the shared state down to entities/article or up into a composite widget.
  • Public API Isolation: Never import from '@/entities/user/ui/subfolder/Component'. Always import exclusively from @/entities/user.
  • #architecture
  • #react
  • #fsd
  • #typescript

Share

Comments

Join the conversation

Sign in with GitHub to leave a comment on Architecting Scalable Frontend Applications with Feature-Sliced Design (FSD).

Pip · Personal AI assistant

What would you like to know?

I'm Pip. I know Saleh's experience, projects, writing, and how to work with him.

Answers are AI-generated and can be wrong.

Attachments

100%