# Feature-Sliced Design ## documentation - [Examples](/examples.md): List of websites people are building with Feature-Sliced Design - [🧭 Navigation](/nav.md): Feature-Sliced Design Navigation help page - [Search the documentation](/search.md) - [Feature-Sliced Design versions](/versions.md): Feature-Sliced Design Versions page listing all documented site versions - [πŸ’« Community](/community.md): Community resources, additional materials - [Team](/community/team.md): Core-team - [Alternatives](/docs/about/alternatives.md): History of architecture approaches - [Mission](/docs/about/mission.md): Here we describe the goals and limitations of the applicability of the methodology-which we are guided by when developing the methodology - [Motivation](/docs/about/motivation.md): The main idea of Feature-Sliced Design is to facilitate and reduce the cost of developing complex and developing projects, based on combining research results, discussing the experience of various kinds of a wide range of developers. - [Promote in company](/docs/about/promote/for-company.md): Do the project and the company need a methodology? - [Promote in team](/docs/about/promote/for-team.md): - Onboard newcomers - [Integration aspects](/docs/about/promote/integration.md): Summary - [Partial Application](/docs/about/promote/partial-application.md): How to partially apply the methodology? Does it make sense? What if I ignore it? - [Abstractions](/docs/about/understanding/abstractions.md): The law of leaky abstractions - [About architecture](/docs/about/understanding/architecture.md): Problems - [Knowledge types in the project](/docs/about/understanding/knowledge-types.md): The following "types of knowledge" can be distinguished in any project: - [Naming](/docs/about/understanding/naming.md): Different developers have different experiences and contexts, which can lead to misunderstandings on the team when the same entities are called differently. For example: - [Needs driven](/docs/about/understanding/needs-driven.md): β€” Can't you formulate the goal that the new feature will solve? Or maybe the problem is that the task itself is not formulated? **The point is also that the methodology helps to pull out the problematic definition of tasks and goals** - [Signals of architecture](/docs/about/understanding/signals.md): If there is a limitation on the part of the architecture, then there are obvious reasons for this, and consequences if they are ignored - [Branding Guidelines](/docs/branding.md): FSD's visual identity is based on its core-concepts: Layered, Sliced self-contained parts, Parts & Compose, Segmented. - [Decomposition cheatsheet](/docs/get-started/cheatsheet.md): Use this as a quick reference when you're deciding how to decompose your UI. PDF versions are also available below, so you can print it out and keep one under your pillow. - [FAQ](/docs/get-started/faq.md): You can ask your question in our Telegram chat, Discord community, and GitHub Discussions. - [Overview](/docs/get-started/overview.md): Feature-Sliced Design (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and stable in the face of ever-changing business requirements. - [Tutorial](/docs/get-started/tutorial.md): Part 1. On paper - [Handling API Requests](/docs/guides/examples/api-requests.md): handling-api-requests} - [Authentication](/docs/guides/examples/auth.md): Broadly, authentication consists of the following steps: - [Autocomplete](/docs/guides/examples/autocompleted.md): About decomposition by layers - [Browser API](/docs/guides/examples/browser-api.md): About working with the Browser API: localStorage, audio Api, bluetooth API, etc. - [CMS](/docs/guides/examples/cms.md): Features may be different - [Feedback](/docs/guides/examples/feedback.md): Errors, Alerts, Notifications, ... - [i18n](/docs/guides/examples/i18n.md): Where to place it? How to work with this? - [Metric](/docs/guides/examples/metric.md): About ways to initialize metrics in the application - [Monorepositories](/docs/guides/examples/monorepo.md): About applicability for mono repositories, about bff, about microapps - [Page layouts](/docs/guides/examples/page-layout.md): This guide examines the abstraction of a page layout β€” when several pages share the same overall structure, and differ only in the main content. - [Desktop/Touch platforms](/docs/guides/examples/platforms.md): About the application of the methodology for desktop/touch - [SSR](/docs/guides/examples/ssr.md): About the implementation of SSR using the methodology - [Theme](/docs/guides/examples/theme.md): Where should I put my work with the theme and palette? - [Types](/docs/guides/examples/types.md): This guide concerns data types from typed languages like TypeScript and describes where they fit within FSD. - [White Labels](/docs/guides/examples/white-labels.md): Figma, brand uikit, templates, adaptability to brands - [Cross-imports](/docs/guides/issues/cross-imports.md): Cross-imports appear when the layer or abstraction begins to take too much responsibility than it should. That is why the methodology identifies new layers that allow you to uncouple these cross-imports - [Desegemented](/docs/guides/issues/desegmented.md): Situation - [Routing](/docs/guides/issues/routes.md): Situation - [Migration from a custom architecture](/docs/guides/migration/from-custom.md): This guide describes an approach that might be helpful when migrating from a custom self-made architecture to Feature-Sliced Design. - [Migration from v1 to v2](/docs/guides/migration/from-v1.md): Why v2? - [Migration from v2.0 to v2.1](/docs/guides/migration/from-v2-0.md): The main change in v2.1 is the new mental model for decomposing an interface β€” pages first. - [Usage with Electron](/docs/guides/tech/with-electron.md): Electron applications have a special architecture consisting of multiple processes with different responsibilities. Applying FSD in such a context requires adapting the structure to the Electron specifics. - [Usage with Next.js](/docs/guides/tech/with-nextjs.md): FSD is compatible with Next.js in both the App Router version and the Pages Router version if you solve the main conflict β€” the app and pages folders. - [Usage with NuxtJS](/docs/guides/tech/with-nuxtjs.md): It is possible to implement FSD in a NuxtJS project, but conflicts arise due to the differences between NuxtJS project structure requirements and FSD principles: - [Usage with React Query](/docs/guides/tech/with-react-query.md): The problem of β€œwhere to put the keys” - [Usage with SvelteKit](/docs/guides/tech/with-sveltekit.md): It is possible to implement FSD in a SvelteKit project, but conflicts arise due to the differences between the structure requirements of a SvelteKit project and the principles of FSD: - [Docs for LLMs](/docs/llms.md): This page provides links and guidance for LLM crawlers. - [Layers](/docs/reference/layers.md): Layers are the first level of organisational hierarchy in Feature-Sliced Design. Their purpose is to separate code based on how much responsibility it needs and how many other modules in the app it depends on. Every layer carries special semantic meaning to help you determine how much responsibility you should allocate to your code. - [Public API](/docs/reference/public-api.md): A public API is a contract between a group of modules, like a slice, and the code that uses it. It also acts as a gate, only allowing access to certain objects, and only through that public API. - [Slices and segments](/docs/reference/slices-segments.md): Slices - [Feature-Sliced Design](/index.md): Architectural methodology for frontend projects --- # Full Documentation Content v2 ![](/documentation/assets/ideal-img/tiny-bunny.dd60f55.640.png) Tiny Bunny Mini Game Mini-game "21 points" in the universe of the visual novel "Tiny Bunny". reactredux-toolkittypescript [Website](https://sanua356.github.io/tiny-bunny/)[Source](https://github.com/sanua356/tiny-bunny) --- # 🧭 Navigation ## Legacy routes After the restructuring of the documentation, some routes were changed. Below you can find the page you may have been looking for. But there are redirects from old links for compatibility ### πŸš€ Get Started ⚑️ Simplified and merged [Tutorial](/documentation/docs/get-started/tutorial.md) [**old**:](/documentation/docs/get-started/tutorial.md) [/docs/get-started/quick-start](/documentation/docs/get-started/tutorial.md) [**new**: ](/documentation/docs/get-started/tutorial.md) [/docs/get-started/tutorial](/documentation/docs/get-started/tutorial.md) [Basics](/documentation/docs/get-started/overview.md) [**old**:](/documentation/docs/get-started/overview.md) [/docs/get-started/basics](/documentation/docs/get-started/overview.md) [**new**: ](/documentation/docs/get-started/overview.md) [/docs/get-started/overview](/documentation/docs/get-started/overview.md) [Decompose Cheatsheet](/documentation/docs/get-started/cheatsheet.md) [**old**:](/documentation/docs/get-started/cheatsheet.md) [/docs/get-started/tutorial/decompose; /docs/get-started/tutorial/design-mockup; /docs/get-started/onboard/cheatsheet](/documentation/docs/get-started/cheatsheet.md) [**new**: ](/documentation/docs/get-started/cheatsheet.md) [/docs/get-started/cheatsheet](/documentation/docs/get-started/cheatsheet.md) ### 🍰 Alternatives ⚑️ Moved and merged to /about/alternatives as advanced materials [Architecture approaches alternatives](/documentation/docs/about/alternatives.md) [**old**:](/documentation/docs/about/alternatives.md) [/docs/about/alternatives/big-ball-of-mud; /docs/about/alternatives/design-principles; /docs/about/alternatives/ddd; /docs/about/alternatives/clean-architecture; /docs/about/alternatives/frameworks; /docs/about/alternatives/atomic-design; /docs/about/alternatives/smart-dumb-components; /docs/about/alternatives/feature-driven](/documentation/docs/about/alternatives.md) [**new**: ](/documentation/docs/about/alternatives.md) [/docs/about/alternatives](/documentation/docs/about/alternatives.md) ### 🍰 Promote & Understanding ⚑️ Moved to /about as advanced materials [Knowledge types](/documentation/docs/about/understanding/knowledge-types.md) [**old**:](/documentation/docs/about/understanding/knowledge-types.md) [/docs/reference/knowledge-types](/documentation/docs/about/understanding/knowledge-types.md) [**new**: ](/documentation/docs/about/understanding/knowledge-types.md) [/docs/about/understanding/knowledge-types](/documentation/docs/about/understanding/knowledge-types.md) [Needs driven](/documentation/docs/about/understanding/needs-driven.md) [**old**:](/documentation/docs/about/understanding/needs-driven.md) [/docs/concepts/needs-driven](/documentation/docs/about/understanding/needs-driven.md) [**new**: ](/documentation/docs/about/understanding/needs-driven.md) [/docs/about/understanding/needs-driven](/documentation/docs/about/understanding/needs-driven.md) [About architecture](/documentation/docs/about/understanding/architecture.md) [**old**:](/documentation/docs/about/understanding/architecture.md) [/docs/concepts/architecture](/documentation/docs/about/understanding/architecture.md) [**new**: ](/documentation/docs/about/understanding/architecture.md) [/docs/about/understanding/architecture](/documentation/docs/about/understanding/architecture.md) [Naming adaptability](/documentation/docs/about/understanding/naming.md) [**old**:](/documentation/docs/about/understanding/naming.md) [/docs/concepts/naming-adaptability](/documentation/docs/about/understanding/naming.md) [**new**: ](/documentation/docs/about/understanding/naming.md) [/docs/about/understanding/naming](/documentation/docs/about/understanding/naming.md) [Signals of architecture](/documentation/docs/about/understanding/signals.md) [**old**:](/documentation/docs/about/understanding/signals.md) [/docs/concepts/signals](/documentation/docs/about/understanding/signals.md) [**new**: ](/documentation/docs/about/understanding/signals.md) [/docs/about/understanding/signals](/documentation/docs/about/understanding/signals.md) [Abstractions of architecture](/documentation/docs/about/understanding/abstractions.md) [**old**:](/documentation/docs/about/understanding/abstractions.md) [/docs/concepts/abstractions](/documentation/docs/about/understanding/abstractions.md) [**new**: ](/documentation/docs/about/understanding/abstractions.md) [/docs/about/understanding/abstractions](/documentation/docs/about/understanding/abstractions.md) ### πŸ“š Reference guidelines (isolation & units) ⚑️ Moved to /reference as theoretical materials (old concepts) [Decouple of entities](/documentation/docs/reference/layers.md#import-rule-on-layers) [**old**:](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/concepts/decouple-entities](/documentation/docs/reference/layers.md#import-rule-on-layers) [**new**: ](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/reference/layers#import-rule-on-layers](/documentation/docs/reference/layers.md#import-rule-on-layers) [Low Coupling & High Cohesion](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) [**old**:](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) [/docs/concepts/low-coupling](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) [**new**: ](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) [/docs/reference/slices-segments#zero-coupling-high-cohesion](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) [Cross-communication](/documentation/docs/reference/layers.md#import-rule-on-layers) [**old**:](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/concepts/cross-communication](/documentation/docs/reference/layers.md#import-rule-on-layers) [**new**: ](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/reference/layers#import-rule-on-layers](/documentation/docs/reference/layers.md#import-rule-on-layers) [App splitting](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/concepts/app-splitting](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Decomposition](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/decomposition](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Units](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Layers](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Layer overview](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/layers/overview](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [App layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/app](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Processes layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/processes](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Pages layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/pages](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Widgets layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/widgets](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Widgets layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/layers/widgets](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Features layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/features](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Entities layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/entities](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Shared layer](/documentation/docs/reference/layers.md) [**old**:](/documentation/docs/reference/layers.md) [/docs/reference/units/layers/shared](/documentation/docs/reference/layers.md) [**new**: ](/documentation/docs/reference/layers.md) [/docs/reference/layers](/documentation/docs/reference/layers.md) [Segments](/documentation/docs/reference/slices-segments.md) [**old**:](/documentation/docs/reference/slices-segments.md) [/docs/reference/units/segments](/documentation/docs/reference/slices-segments.md) [**new**: ](/documentation/docs/reference/slices-segments.md) [/docs/reference/slices-segments](/documentation/docs/reference/slices-segments.md) ### 🎯 Bad Practices handbook ⚑️ Moved to /guides as practice materials [Cross-imports](/documentation/docs/guides/issues/cross-imports.md) [**old**:](/documentation/docs/guides/issues/cross-imports.md) [/docs/concepts/issues/cross-imports](/documentation/docs/guides/issues/cross-imports.md) [**new**: ](/documentation/docs/guides/issues/cross-imports.md) [/docs/guides/issues/cross-imports](/documentation/docs/guides/issues/cross-imports.md) [Desegmented](/documentation/docs/guides/issues/desegmented.md) [**old**:](/documentation/docs/guides/issues/desegmented.md) [/docs/concepts/issues/desegmented](/documentation/docs/guides/issues/desegmented.md) [**new**: ](/documentation/docs/guides/issues/desegmented.md) [/docs/guides/issues/desegmented](/documentation/docs/guides/issues/desegmented.md) [Routes](/documentation/docs/guides/issues/routes.md) [**old**:](/documentation/docs/guides/issues/routes.md) [/docs/concepts/issues/routes](/documentation/docs/guides/issues/routes.md) [**new**: ](/documentation/docs/guides/issues/routes.md) [/docs/guides/issues/routes](/documentation/docs/guides/issues/routes.md) ### 🎯 Examples ⚑️ Grouped and simplified into /guides/examples as practical examples [Viewer logic](/documentation/docs/guides/examples/auth.md) [**old**:](/documentation/docs/guides/examples/auth.md) [/docs/guides/examples/viewer](/documentation/docs/guides/examples/auth.md) [**new**: ](/documentation/docs/guides/examples/auth.md) [/docs/guides/examples/auth](/documentation/docs/guides/examples/auth.md) [Monorepo](/documentation/docs/guides/examples/monorepo.md) [**old**:](/documentation/docs/guides/examples/monorepo.md) [/docs/guides/monorepo](/documentation/docs/guides/examples/monorepo.md) [**new**: ](/documentation/docs/guides/examples/monorepo.md) [/docs/guides/examples/monorepo](/documentation/docs/guides/examples/monorepo.md) [White Labels](/documentation/docs/guides/examples/white-labels.md) [**old**:](/documentation/docs/guides/examples/white-labels.md) [/docs/guides/white-labels](/documentation/docs/guides/examples/white-labels.md) [**new**: ](/documentation/docs/guides/examples/white-labels.md) [/docs/guides/examples/white-labels](/documentation/docs/guides/examples/white-labels.md) ### 🎯 Migration ⚑️ Grouped and simplified into /guides/migration as migration guidelines [Migration from V1](/documentation/docs/guides/migration/from-v1.md) [**old**:](/documentation/docs/guides/migration/from-v1.md) [/docs/guides/migration-from-v1](/documentation/docs/guides/migration/from-v1.md) [**new**: ](/documentation/docs/guides/migration/from-v1.md) [/docs/guides/migration/from-v1](/documentation/docs/guides/migration/from-v1.md) [Migration from Legacy](/documentation/docs/guides/migration/from-custom.md) [**old**:](/documentation/docs/guides/migration/from-custom.md) [/docs/guides/migration-from-legacy](/documentation/docs/guides/migration/from-custom.md) [**new**: ](/documentation/docs/guides/migration/from-custom.md) [/docs/guides/migration/from-custom](/documentation/docs/guides/migration/from-custom.md) ### 🎯 Tech ⚑️ Grouped into /guides/tech as tech-specific usage guidelines [Usage with NextJS](/documentation/docs/guides/tech/with-nextjs.md) [**old**:](/documentation/docs/guides/tech/with-nextjs.md) [/docs/guides/usage-with-nextjs](/documentation/docs/guides/tech/with-nextjs.md) [**new**: ](/documentation/docs/guides/tech/with-nextjs.md) [/docs/guides/tech/with-nextjs](/documentation/docs/guides/tech/with-nextjs.md) ### Rename 'legacy' to 'custom' ⚑️ 'Legacy' is derogatory, we don't get to call people's projects legacy [Rename 'legacy' to custom](/documentation/docs/guides/migration/from-custom.md) [**old**:](/documentation/docs/guides/migration/from-custom.md) [/docs/guides/migration/from-legacy](/documentation/docs/guides/migration/from-custom.md) [**new**: ](/documentation/docs/guides/migration/from-custom.md) [/docs/guides/migration/from-custom](/documentation/docs/guides/migration/from-custom.md) ### Deduplication of Reference ⚑️ Cleaned up the Reference section and deduplicated the material [Isolation of modules](/documentation/docs/reference/layers.md#import-rule-on-layers) [**old**:](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/reference/isolation](/documentation/docs/reference/layers.md#import-rule-on-layers) [**new**: ](/documentation/docs/reference/layers.md#import-rule-on-layers) [/docs/reference/layers#import-rule-on-layers](/documentation/docs/reference/layers.md#import-rule-on-layers) --- [Skip to main content](#__docusaurus_skipToContent_fallback) [![logo](/documentation/img/brand/logo-primary.png)![logo](/documentation/img/brand/logo-primary.png)](/documentation/.md) [****](/documentation/.md)[πŸ“– Docs](/documentation/docs/get-started/overview.md)[πŸ’« Community](/documentation/community.md)[πŸ“ Blog](/documentation/blog)[πŸ›  Examples](/documentation/examples.md) [v2.1](/documentation/docs/get-started/overview.md) * [v2.1](/documentation/docs/get-started/overview.md) * [v1.0](https://feature-sliced.github.io/featureslices.dev/v1.0.html) * [v0.1](https://feature-sliced.github.io/featureslices.dev/v0.1.html) * [feature-driven](https://github.com/feature-sliced/documentation/tree/rc/feature-driven) * [All versions](/documentation/versions.md) [English](#) * [Русский](/documentation/ru/search) * [English](/documentation/search.md) * [O'zbekcha](/documentation/uz/search) * [ν•œκ΅­μ–΄](/documentation/kr/search) * [ζ—₯本θͺž](/documentation/ja/search) * [Help Us Translate](https://github.com/feature-sliced/documentation/issues/244) [](https://discord.gg/S8MzWTUsmp)[](https://github.com/feature-sliced/documentation) Search # Search the documentation Type your search here [](https://www.algolia.com/) Specs * [Documentation](/documentation/docs/get-started/overview.md) * [Community](/documentation/community.md) * [Help](/documentation/nav.md) * [Discussions](https://github.com/feature-sliced/documentation/discussions) Community * [Discord](https://discord.gg/S8MzWTUsmp) * [Telegram (RU)](https://t.me/feature_sliced) * [Twitter](https://twitter.com/feature_sliced) * [Open Collective](https://opencollective.com/feature-sliced) * [YouTube](https://www.youtube.com/c/FeatureSlicedDesign) More * [GitHub](https://github.com/feature-sliced) * [Contribution Guide](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md) * [License](https://github.com/feature-sliced/documentation/blob/master/LICENSE) * [Docs for LLMs](/documentation/docs/llms.md) [![Feature-Sliced Design - Architectural methodology for frontend projects](/documentation/img/brand/logo-primary.png)![Feature-Sliced Design - Architectural methodology for frontend projects](/documentation/img/brand/logo-primary.png)](https://github.com/feature-sliced) Copyright Β© 2018-2025 Feature-Sliced Design --- # Feature-Sliced Design versions ### Feature-Sliced Design v2.1 (Current) The documentation for the currently published version can be found here | v2.1 | [Release Notes](https://github.com/feature-sliced/documentation/releases/tag/v2.1) | [Documentation](/documentation/docs/get-started/overview.md) | [Migration from v1](/documentation/docs/guides/migration/from-v1.md) | [Migration from v2.0](/documentation/docs/guides/migration/from-v1.md) | | ---- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------- | ---------------------------------------------------------------------- | ### Feature Slices v1 (Legacy) Documentation for older versions of feature-slices can be found here | v1.0 | [Documentation](https://feature-sliced.github.io/featureslices.dev/v1.0.html) | | ---- | ----------------------------------------------------------------------------- | | v0.1 | [Documentation](https://feature-sliced.github.io/featureslices.dev/v0.1.html) | ### Feature Driven (Legacy) Documentation for older versions of feature-driven can be found here | v0.1 | [Documentation](https://github.com/feature-sliced/documentation/tree/rc/feature-driven) | | ------------- | --------------------------------------------------------------------------------------- | | Example (kof) | [Github](https://github.com/kof/feature-driven-architecture) | --- # πŸ’« Community Community resources, additional materials ## Main[​](#main "Direct link to heading") [Awesome Resources](https://github.com/feature-sliced/awesome) [A curated list of awesome FSD videos, articles, packages](https://github.com/feature-sliced/awesome) [Team](/documentation/community/team.md) [Core-team, Champions, Contributors, Companies](/documentation/community/team.md) [Brandbook](/documentation/docs/branding.md) [Recommendations for FSD's branding usage](/documentation/docs/branding.md) [Contributing](#) [HowTo, Workflow, Support](#) --- # Team WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/192) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Core-team[​](#core-team "Direct link to heading") ### Champions[​](#champions "Direct link to heading") ## Contributors[​](#contributors "Direct link to heading") ## Companies[​](#companies "Direct link to heading") --- # Alternatives WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/62) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* History of architecture approaches ## Big Ball of Mud[​](#big-ball-of-mud "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/258) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > What is it; Why is it so common; When it starts to bring problems; What to do and how does FSD help in this * [(Article) Oleg Isonen - Last words on UI architecture before an AI takes over](https://oleg008.medium.com/last-words-on-ui-architecture-before-an-ai-takes-over-468c78f18f0d) * [(Report) Julia Nikolaeva, iSpring - Big Ball of Mud and other problems of the monolith, we have handled](http://youtu.be/gna4Ynz1YNI) * [(Article) DD - Big Ball of mud](https://thedomaindrivendesign.io/big-ball-of-mud/) ## Smart & Dumb components[​](#smart--dumb-components "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/214) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the approach; About applicability in the frontend; Methodology position About obsolescence, about a new view from the methodology Why component-containers approach is evil? * [(Article) Den Abramov-Presentation and Container Components (TLDR: deprecated)](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) ## Design Principles[​](#design-principles "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/59) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > What are we talking about; FSD position SOLID, GRASP, KISS, YAGNI, ... - and why they don't work well together in practice And how does it aggregate these practices * [(Talk) Ilya Azin - Feature-Sliced Design (fragment about Design Principles)](https://youtu.be/SnzPAr_FJ7w?t=380) ## DDD[​](#ddd "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/1) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the approach; Why does it work poorly in practice What is the difference, how does it improve applicability, where does it adopt practices * [(Article) DDD, Hexagonal, Onion, Clean, CQRS, ... How I put it all together](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) * [(Talk) Ilya Azin - Feature-Sliced Design (fragment about Clean Architecture, DDD)](https://youtu.be/SnzPAr_FJ7w?t=528) ## Clean Architecture[​](#clean-architecture "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/165) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the approach; About applicability in the frontend; FSD position How are they similar (to many), how are they different * [(Thread) About use-case/interactor in the methodology](https://t.me/feature_sliced/3897) * [(Thread) About DI in the methodology](https://t.me/feature_sliced/4592) * [(Article) Alex Bespoyasov - Clean Architecture on frontend](https://bespoyasov.me/blog/clean-architecture-on-frontend/) * [(Article) DDD, Hexagonal, Onion, Clean, CQRS, ... How I put it all together](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) * [(Talk) Ilya Azin - Feature-Sliced Design (fragment about Clean Architecture, DDD)](https://youtu.be/SnzPAr_FJ7w?t=528) * [(Article) Misconceptions of Clean Architecture](http://habr.com/ru/company/mobileup/blog/335382/) ## Frameworks[​](#frameworks "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/58) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About applicability in the frontend; Why frameworks do not solve problems; why there is no single approach; FSD position Framework-agnostic, conventional-approach * [(Article) About the reasons for creating the methodology (fragment about frameworks)](/documentation/docs/about/motivation.md) * [(Thread) About the applicability of the methodology for different frameworks](https://t.me/feature_sliced/3867) ## Atomic Design[​](#atomic-design "Direct link to heading") ### What is it?[​](#what-is-it "Direct link to heading") In Atomic Design, the scope of responsibility is divided into standardized layers. Atomic Design is broken down into **5 layers** (from top to bottom): 1. `pages` - Functionality similar to the `pages` layer in FSD. 2. `templates` - Components that define the structure of a page without tying to specific content. 3. `organisms` - Modules consisting of molecules that have business logic. 4. `molecules` - More complex components that generally do not contain business logic. 5. `atoms` - UI components without business logic. Modules at one layer interact only with modules in the layers below, similar to FSD. That is, molecules are built from atoms, organisms from molecules, templates from organisms, and pages from templates. Atomic Design also implies the use of Public API within modules for isolation. ### Applicability to frontend[​](#applicability-to-frontend "Direct link to heading") Atomic Design is relatively common in projects. Atomic Design is more popular among web designers than in development. Web designers often use Atomic Design to create scalable and easily maintainable designs. In development, Atomic Design is often mixed with other architectural methodologies. However, since Atomic Design focuses on UI components and their composition, a problem arises with implementing business logic within the architecture. The problem is that Atomic Design does not provide a clear level of responsibility for business logic, leading to its distribution across various components and levels, complicating maintenance and testing. The business logic becomes blurred, making it difficult to clearly separate responsibilities and rendering the code less modular and reusable. ### How does it relate to FSD?[​](#how-does-it-relate-to-fsd "Direct link to heading") In the context of FSD, some elements of Atomic Design can be applied to create flexible and scalable UI components. The `atoms` and `molecules` layers can be implemented in `shared/ui` in FSD, simplifying the reuse and maintenance of basic UI elements. ``` β”œβ”€β”€ shared β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”œβ”€β”€ atoms β”‚ β”‚ β”œβ”€β”€ molecules β”‚ ... ``` A comparison of FSD and Atomic Design shows that both methodologies strive for modularity and reusability but focus on different aspects. Atomic Design is oriented towards visual components and their composition. FSD focuses on dividing the application's functionality into independent modules and their interconnections. * [Atomic Design Methodology](https://atomicdesign.bradfrost.com/table-of-contents/) * [(Thread) About applicability in shared / ui](https://t.me/feature_sliced/1653) * [(Video) Briefly about Atomic Design](https://youtu.be/Yi-A20x2dcA) * [(Talk) Ilya Azin - Feature-Sliced Design (fragment about Atomic Design)](https://youtu.be/SnzPAr_FJ7w?t=587) ## Feature Driven[​](#feature-driven "Direct link to heading") WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/219) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the approach; About applicability in the frontend; FSD position About compatibility, historical development and comparison * [(Talk) Oleg Isonen - Feature Driven Architecture](https://youtu.be/BWAeYuWFHhs) * [Feature Driven-Short specification (from the point of view of FSD)](https://github.com/feature-sliced/documentation/tree/rc/feature-driven) --- # Mission Here we describe the goals and limitations of the applicability of the methodology-which we are guided by when developing the methodology * We see our goal as a balance between ideology and simplicity * We won't be able to make a silver bullet that fits everyone **Nevertheless, the methodology should be close and accessible to a fairly wide range of developers** ## Goals[​](#goals "Direct link to heading") ### Intuitive clarity for a wide range of developers[​](#intuitive-clarity-for-a-wide-range-of-developers "Direct link to heading") The methodology should be accessible - for most of the team in projects *Because even with all the future tools , it will not be enough, if only experienced seniors/leads will understand the methodology* ### Solving everyday problems[​](#solving-everyday-problems "Direct link to heading") The methodology should set out the reasons and solutions to our everyday problems when developing projects **And also-attach tools to all this (cli, linters)** So that developers can use a *battle-tested* approach that allows them to bypass long-standing problems of architecture and development > *@sergeysova: Imagine, that a developer writes code within the framework of the methodology and he has problems 10 times less often, simply because other people have thought out the solution to many problems.* ## Limitations[​](#limitations "Direct link to heading") We do not want to *impose our point of view*, and at the same time we understand that *many of our habits, as developers, interfere from day to day* Everyone has their own level of experience in designing and developing systems, **therefore, it is worth understanding the following:** * **Will not work**: very simple, very clear, for everyone > *@sergeysova: Some concepts cannot be intuitively understood until you encounter problems and spend years solving them.* > > * *In math world: is graph theory.* > * *In physics: quantum mechanics.* > * *In programming: application architecture.* * **Possible and desirable**: simplicity, extensibility ## See also[​](#see-also "Direct link to heading") * [Architecture problems](/documentation/docs/about/understanding/architecture.md#problems) --- # Motivation The main idea of **Feature-Sliced Design** is to facilitate and reduce the cost of developing complex and developing projects, based on [combining research results, discussing the experience of various kinds of a wide range of developers](https://github.com/feature-sliced/documentation/discussions). Obviously, this will not be a silver bullet, and of course, the methodology will have its own [limits of applicability](/documentation/docs/about/mission.md). Nevertheless, there are reasonable questions regarding *the feasibility of such a methodology as a whole* note More details [discussed in the discussion](https://github.com/feature-sliced/documentation/discussions/27) ## Why are there not enough existing solutions?[​](#why-are-there-not-enough-existing-solutions "Direct link to heading") > It usually, these arguments: > > * *"Why you need some new methodology, if you already have long-established approaches and principles of design such as `SOLID`, `KISS`, `YAGNI`, `DDD`, `GRASP`, `DRY`, etc."* > * *"All the problems are solved by good project documentation, tests, and structured processes"* > * *"Problems would not have happened if all developers are following all the above"* > * *"Everything was invented before you, you just can't use it"* > * *"Take {FRAMEWORK\_NAME} - everything has already been decided for you there"* ### Principles alone are not enough[​](#principles-alone-are-not-enough "Direct link to heading") **The existence of principles alone is not enough to design a good architecture** Not everyone knows them completely, even fewer understand and apply them correctly *The design principles are too general, and do not give a specific answer to the question: "How to design the structure and architecture of a scalable and flexible application?"* ### Processes don't always work[​](#processes-dont-always-work "Direct link to heading") *Documentation/Tests/Processes* are, of course, good, but alas, even at high costs for them - **they do not always solve the problems posed by the architecture and the introduction of new people into the project** * The time of entry of each developer into the project is not greatly reduced, because the documentation will most often come out huge / outdated * Constantly make sure that everyone understands architecture in the same way-it also requires a huge amount of resources * Do not forget about the bus-factor ### Existing frameworks cannot be applied everywhere[​](#existing-frameworks-cannot-be-applied-everywhere "Direct link to heading") * Existing solutions usually have a high entry threshold, which makes it difficult to find new developers * Also, most often, the choice of technology has already been determined before the onset of serious problems in the project, and therefore you need to be able to "work with what is" - **without being tied to the technology** > Q: *"In my project `React/Vue/Redux/Effector/Mobx/{YOUR_TECH}` - how can I better build the structure of entities and the relationships between them?"* ### As a result[​](#as-a-result "Direct link to heading") We get *"unique as snowflakes"* projects, each of which requires a long immersion of the employee, and knowledge that is unlikely to be applicable on another project > @sergeysova: *"This is exactly the situation that currently exists in our field of frontend development: each lead will invent different architectures and project structures, while it is not a fact that these structures will pass the test of time, as a result, a maximum of two people can develop the project besides him, and each new developer needs to be immersed again."* ## Why do developers need the methodology?[​](#why-do-developers-need-the-methodology "Direct link to heading") ### Focus on business features, not on architecture problems[​](#focus-on-business-features-not-on-architecture-problems "Direct link to heading") The methodology allows you to save resources on designing a scalable and flexible architecture, instead directing the attention of developers to the development of the main functionality. At the same time, the architectural solutions themselves are standardized from project to project. *A separate question is that the methodology should earn the trust of the community, so that another developer can get acquainted with it and rely on it in solving the problems of his project within the time available to him* ### An experience-proven solution[​](#an-experience-proven-solution "Direct link to heading") The methodology is designed for developers who are aimed at *a proven solution for designing complex business logic* *However, it is clear that the methodology is generally about a set of best-practices, articles that address certain problems and cases during development. Therefore, the methodology will also be useful for the rest of the developers-who somehow face problems during development and design* ### Project Health[​](#project-health "Direct link to heading") The methodology will allow *to solve and track the problems of the project in advance, without requiring a huge amount of resources* **Most often, technical debt accumulates and accumulates over time, and the responsibility for its resolution lies on both the lead and the team** The methodology will allow you to *warn* possible problems in the scaling and development of the project in advance ## Why does a business need a methodology?[​](#why-does-a-business-need-a-methodology "Direct link to heading") ### Fast onboarding[​](#fast-onboarding "Direct link to heading") With the methodology, you can hire a person to the project who **is already previously familiar with this approach, and not train again** *People start to understand and benefit the project faster, and there are additional guarantees to find people for the next iterations of the project* ### An experience-proven solution[​](#an-experience-proven-solution-1 "Direct link to heading") With the methodology, the business will get *a solution for most of the issues that arise during the development of systems* Since most often a business wants to get a framework / solution that would solve the lion's share of problems during the development of the project ### Applicability for different stages of the project[​](#applicability-for-different-stages-of-the-project "Direct link to heading") The methodology can benefit the project *both at the stage of project support and development, and at the MVP stage* Yes, the most important thing for MVP is *"features, not the architecture laid down for the future"*. But even in conditions of limited deadlines, knowing the best-practices from the methodology, you can *"do with little blood"*, when designing the MVP version of the system, finding a reasonable compromise (rather than modeling features "at random") *The same can be said about testing* ## When is our methodology not needed?[​](#when-is-our-methodology-not-needed "Direct link to heading") * If the project will live for a short time * If the project does not need a supported architecture * If the business does not perceive the connection between the code base and the speed of feature delivery * If it is more important for the business to close orders as soon as possible, without further support ### Business Size[​](#business-size "Direct link to heading") * **Small business** - most often needs a ready-made and very fast solution. Only when the business grows (at least to almost average), he understands that in order for customers to continue using, it is necessary, among other things, to devote time to the quality and stability of the solutions being developed * **Medium-sized business** - usually understands all the problems of development, and even if it is necessary to *"arrange a race for features"*, he still spends time on quality improvements, refactoring and tests (and of course-on an extensible architecture) * **Big business** - usually already has an extensive audience, staff, and a much more extensive set of its practices, and probably even its own approach to architecture, so the idea of taking someone else's comes to them not so often ## Plans[​](#plans "Direct link to heading") The main part of the goals [is set out here](/documentation/docs/about/mission.md#goals), but in addition, it is worth talking about our expectations from the methodology in the future ### Combining experience[​](#combining-experience "Direct link to heading") Now we are trying to combine all our diverse experience of the `core-team`, and get a methodology hardened by practice as a result Of course, we can get Angular 3.0 as a result, but it is much more important here to **investigate the very problem of designing the architecture of complex systems** *And yes - we have complaints about the current version of the methodology, but we want to work together to come to a single and optimal solution (taking into account, among other things, the experience of the community)* ### Life outside the specification[​](#life-outside-the-specification "Direct link to heading") If everything goes well, then the methodology will not be limited only to the specification and the toolkit * Perhaps there will be reports, articles * There may be `CODE_MODEs` for migrations to other technologies of projects written according to the methodology * It is possible that as a result we will be able to reach the maintainers of large technological solutions * *Especially for React, compared to other frameworks - this is the main problem, because it does not say how to solve certain problems* ## See also[​](#see-also "Direct link to heading") * [(Discussion) Don't need a methodology?](https://github.com/feature-sliced/documentation/discussions/27) * [About the methodology's mission: goals and limitations](/documentation/docs/about/mission.md) * [Types of knowledge in the project](/documentation/docs/about/understanding/knowledge-types.md) --- # Promote in company WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/206) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Do the project and the company need a methodology?[​](#do-the-project-and-the-company-need-a-methodology "Direct link to heading") > About the justification of the application, Those duty ## How can I submit a methodology to a business?[​](#how-can-i-submit-a-methodology-to-a-business "Direct link to heading") ## How to prepare and justify a plan to move to the methodology?[​](#how-to-prepare-and-justify-a-plan-to-move-to-the-methodology "Direct link to heading") --- # Promote in team WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/182) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* * Onboard newcomers * Development Guidelines ("where to search N module", etc...) * New approach for tasks ## See also[​](#see-also "Direct link to heading") * [(Thread) The simplicity of the old approaches and the importance of mindfulness](https://t.me/feature_sliced/3360) * [(Thread) About the convenience of searching by layers](https://t.me/feature_sliced/1918) --- # Integration aspects ## Summary[​](#summary "Direct link to heading") First 5 minutes (RU): [YouTube video player](https://www.youtube.com/embed/TFA6zRO_Cl0?start=2110) ## Also[​](#also "Direct link to heading") **Advantages**: * [Overview](/documentation/docs/get-started/overview.md) * CodeReview * Onboarding **Disadvantages:** * Mental complexity * High entry threshold * "Layers hell" * Typical problems of feature-based approaches --- # Partial Application WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/199) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > How to partially apply the methodology? Does it make sense? What if I ignore it? --- # Abstractions WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/186) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## The law of leaky abstractions[​](#the-law-of-leaky-abstractions "Direct link to heading") ## Why are there so many abstractions[​](#why-are-there-so-many-abstractions "Direct link to heading") > Abstractions help to cope with the complexity of the project. The question is - will these abstractions be specific only for this project, or will we try to derive general abstractions based on the specifics of the frontend > Architecture and applications in general are inherently complex, and the only question is how to better distribute and describe this complexity ## About scopes of responsibility[​](#about-scopes-of-responsibility "Direct link to heading") > About optional abstractions ## See also[​](#see-also "Direct link to heading") * [About the need for new layers](https://t.me/feature_sliced/2801) * [About the difficulty in understanding the methodology and layers](https://t.me/feature_sliced/2619) --- # About architecture ## Problems[​](#problems "Direct link to heading") Usually, the conversation about architecture is raised when the development stops due to certain problems in the project. ### Bus-factor & Onboarding[​](#bus-factor--onboarding "Direct link to heading") Only a limited number of people understand the project and its architecture **Examples:** * *"It's difficult to add a person to the development"* * *"For every problem, everyone has their own opinion on how to get around" (let's envy the angular)* * *"I don't understand what is happening in this big piece of monolith"* ### Implicit and uncontrolled consequences[​](#implicit-and-uncontrolled-consequences "Direct link to heading") A lot of implicit side effects during development/refactoring *("everything depends on everything")* **Examples:** * *"The feature imports the feature"* * *"I updated the store of one page, and the functionality fell off on the other"* * *"The logic is smeared all over the application, and it is impossible to track where the beginning is, where the end is"* ### Uncontrolled reuse of logic[​](#uncontrolled-reuse-of-logic "Direct link to heading") It is difficult to reuse/modify existing logic At the same time, there are usually [two extremes](https://github.com/feature-sliced/documentation/discussions/14): * Either the logic is written completely from scratch for each module *(with possible repetitions in the existing codebase)* * Either there is a tendency to transfer all-all implemented modules to `shared` folders, thereby creating a large dump of modules *from it (where most are used only in one place)* **Examples:** * *"I have **N** implementations of the same business logic in my project, for which I still pay"* * *"There are 6 different components of the button/pop-up/... In the project"* * *"Dump of helpers"* ## Requirements[​](#requirements "Direct link to heading") Therefore, it seems logical to present the desired *requirements for an ideal architecture:* note Wherever it says "easy", it means "relatively easy for a wide range of developers", because it is clear that [it will not be possible to make an ideal solution for absolutely everyone](/documentation/docs/about/mission.md#limitations) ### Explicitness[​](#explicitness "Direct link to heading") * It should be **easy to master and explain** the project and its architecture to the team * The structure should reflect the real **business values of the project** * There must be explicit **side effects and connections** between abstractions * It should be **easy to detect duplicate logic** without interfering with unique implementations * There should be no **dispersion of logic** throughout the project * There should not be **too many heterogeneous abstractions and rules** for a good architecture ### Control[​](#control "Direct link to heading") * A good architecture should **speed up the solution of tasks, the introduction of features** * It should be possible to control the development of the project * It should be easy to **expand, modify, delete the code** * The \* decomposition and isolation of\*\* functionality must be observed * Each component of the system must be **easily replaceable and removable** * *[No need to optimize for changes](https://youtu.be/BWAeYuWFHhs?t=1631) - we can't predict the future* * *[Better-optimize for deletion](https://youtu.be/BWAeYuWFHhs?t=1666) - based on the context that already exists* ### Adaptability[​](#adaptability "Direct link to heading") * A good architecture should be applicable **to most projects** * *With existing infrastructure solutions* * *At any stage of development* * There should be no dependence on the framework and platform * It should be possible to **easily scale the project and the team**, with the possibility of parallelization of development * It should be easy **to adapt to changing requirements and circumstances** ## See also[​](#see-also "Direct link to heading") * [(React Berlin Talk) Oleg Isonen - Feature Driven Architecture](https://youtu.be/BWAeYuWFHhs) * [(React SPB Meetup #1) Sergey Sova - Feature Slices](https://t.me/feature_slices) * [(Article) About project modularization](https://alexmngn.medium.com/why-react-developers-should-modularize-their-applications-d26d381854c1) * [(Article) About Separation of Concerns and structuring by features](https://ryanlanciaux.com/blog/2017/08/20/a-feature-based-approach-to-react-development/) --- # Knowledge types in the project The following "types of knowledge" can be distinguished in any project: * **Fundamental knowledge**
Knowledge that does not change much over time, such as algorithms, computer science, programming language mechanisms and its APIs. * **Technology stack**
Knowledge of the set of technical solutions used in a project, including programming languages, frameworks, and libraries. * **Project knowledge**
Knowledge that is specific to the current project and not valuable outside of it. This knowledge is essential for newly-onboarded developers to be able to contribute effectively. note **Feature-Sliced Design** is designed to reduce reliance on "project knowledge", take more responsibility, and make it easier to onboard new team members. ## See also[​](#see-also "Direct link to heading") * [(Video πŸ‡·πŸ‡Ί) Ilya Klimov - On Types of Knowledge](https://youtu.be/4xyb_tA-uw0?t=249) --- # Naming Different developers have different experiences and contexts, which can lead to misunderstandings on the team when the same entities are called differently. For example: * Components for display can be called "ui", "components", "ui-kit", "views", … * The code that is reused throughout the application can be called "core", "shared", "app", … * Business logic code can be called "store", "model", "state", … ## Naming in Feature-Sliced Design[​](#naming-in-fsd "Direct link to heading") The methodology uses specific terms such as: * "app", "process", "page", "feature", "entity", "shared" as layer names, * "ui', "model", "lib", "api", "config" as segment names. It is very important to stick to these terms to prevent confusion among team members and new developers joining the project. Using standard names also helps when asking for help from the community. ## Naming Conflicts[​](#when-can-naming-interfere "Direct link to heading") Naming conflicts can occur when terms used in the FSD methodology overlap with terms used in the business: * `FSD#process` vs simulated process in an application, * `FSD#page` vs log page, * `FSD#model` vs car model. For example, a developer who sees the word "process" in the code will spend extra time trying to figure out what process is meant. Such **collisions can disrupt the development process**. When the project glossary contains terminology specific to FSD, it is critical to be careful when discussing these terms with the team and technical disinterested parties. To communicate effectively with the team, it is recommended that the abbreviation "FSD" be used to prefix the methodology terms. For example, when talking about a process, you might say, "We can put this process on the FSD features layer." Conversely, when communicating with non-technical stakeholders, it is better to limit the use of FSD terminology and refrain from mentioning the internal structure of the code base. ## See also[​](#see-also "Direct link to heading") * [(Discussion) Adaptability of naming](https://github.com/feature-sliced/documentation/discussions/16) * [(Discussion) Entity Naming Survey](https://github.com/feature-sliced/documentation/discussions/31#discussioncomment-464894) * [(Discussion) "processes" vs "flows" vs ...](https://github.com/feature-sliced/documentation/discussions/20) * [(Discussion) "model" vs "store" vs ...](https://github.com/feature-sliced/documentation/discussions/68) --- # Needs driven TL;DR β€” *Can't you formulate the goal that the new feature will solve? Or maybe the problem is that the task itself is not formulated? **The point is also that the methodology helps to pull out the problematic definition of tasks and goals*** β€” *project does not live in static - requirements and functionality are constantly changing. Over time, the code turns into mush, because at the start the project was designed only for the initial impression of wishes. **And the task of a good architecture is also to be sharpened for changing development conditions.*** ## Why?[​](#why "Direct link to heading") To choose a clear name for an entity and understand its components, **you need to clearly understand what task will be solved with the help of all this code.** > *@sergeysova: During development, we try to give each entity or function a name that clearly reflects the intentions and meaning of the code being executed.* *After all, without understanding the task, it is impossible to write the right tests that cover the most important cases, put down errors that help the user in the right places, even it is banal not to interrupt the user's flow because of fixable non-critical errors.* ## What tasks are we talking about?[​](#what-tasks-are-we-talking-about "Direct link to heading") Frontend develops applications and interfaces for end users, so we solve the tasks of these consumers. When a person comes to us, **he wants to solve some of his pain or close a need.** *The task of managers and analysts is to formulate this need, and implement developers taking into account the features of web development (loss of communication, backend error, typo, missed the cursor or finger).* **This very goal, with which the user came, is the task of the developers.** > *One small solved problem is a feature in the Feature-Sliced Design methodology β€” you need to cut the entire scope of project tasks into small goals.* ## How does this affect development?[​](#how-does-this-affect-development "Direct link to heading") ### Task decomposition[​](#task-decomposition "Direct link to heading") When a developer begins to implement a task, in order to simplify the understanding and support of the code, he mentally **cuts it into stages**: * first *split into top-level entities* and *implement them*, * then these entities *split into smaller ones* * and so on *In the process of splitting into entities, the developer is forced to give them a name that would clearly reflect his idea and help to understand what task the code solves when reading the listing* *At the same time, we do not forget that we are trying to help the user reduce pain or realize needs* ### Understanding the essence of the task[​](#understanding-the-essence-of-the-task "Direct link to heading") But to give a clear name to an entity, **the developer must know enough about its purpose** * how is he going to use this entity, * what part of the user's task does it implement, where else can this entity be applied, * in what other tasks can it participate, * and so on It is not difficult to draw a conclusion: **while the developer will reflect on the name of entities within the framework of the methodology, he will be able to find poorly formulated tasks even before writing the code.** > How to give a name to an entity if you do not understand well what tasks it can solve, how can you even divide a task into entities if you do not understand it well? ## How to formulate it?[​](#how-to-formulate-it "Direct link to heading") **To formulate a task that is solved by features, you need to understand the task itself**, and this is already the responsibility of the project manager and analysts. *The methodology can only tell the developer what tasks the product manager should pay close attention to.* > *@sergeysova: the Whole frontend is primarily a display of information, any component in the first turn, displays, and then the task "to show the user something" has no practical value.* > > *Even without taking into account the specifics of the frontend can ask, "why do I have to show you", so you can continue to ask until't get out of pain or the need of the consumer.* As soon as we were able to get to the basic needs or pains, we can go back and figure out **how exactly your product or service can help the user with his goals** Any new task in your tracker is aimed at solving business problems, and the business tries to solve the user's tasks at the same time earning money on it. This means that each task has certain goals, even if they are not spelled out in the description text. ***The developer must clearly understand what goal this or that task is pursuing**, but not every company can afford to build processes perfectly, although this is a separate conversation, nevertheless, the developer may well "ping" the right managers himself to find out this and do his part of the work effectively.* ## And what is the benefit?[​](#and-what-is-the-benefit "Direct link to heading") Now let's look at the whole process from beginning to end. ### 1. Understanding user tasks[​](#1-understanding-user-tasks "Direct link to heading") When a developer understands his pain and how the business closes them, he can offer solutions that are not available to the business due to the specifics of web development. > But of course, all this can work only if the developer is not indifferent to what he is doing and for what, otherwise *why then the methodology and some approaches?* ### 2. Structuring and ordering[​](#2-structuring-and-ordering "Direct link to heading") With the understanding of tasks comes **a clear structure both in the head and in the tasks along with the code** ### 3. Understanding the feature and its components[​](#3-understanding-the-feature-and-its-components "Direct link to heading") **One feature is one useful functionality for the user** * When several features are implemented in one feature, this is **a violation of borders** * The feature can be indivisible and growing - **and this is not bad** * **Bad** - when the feature does not answer the question *"What is the business value for the user?"* * There can be no "map-office" feature * But `booking-meeting-on-the-map`, `search-for-an-employee`, `change-of-workplace` - **yes** > *@sergeysova: The point is that the feature contains only code that implements the functionality itself*, without unnecessary details and internal solutions (ideally)\* > > *Open the feature code **and see only what relates to the task** - no more* ### 4. Profit[​](#4-profit "Direct link to heading") Business very rarely turns its course radically in the other direction, which means **the reflection of business tasks in the frontend application code is a very significant profit.** *Then you don't have to explain to each new team member what this or that code does, and in general why it was added - **everything will be explained through the business tasks that are already reflected in the code.*** > What is called ["Business Language" in Domain Driven Development](https://thedomaindrivendesign.io/developing-the-ubiquitous-language) *** ## Back to reality[​](#back-to-reality "Direct link to heading") If business processes are understood and good names are given at the design stage - *then it is not particularly problematic to transfer this understanding and logic to the code.* **However, in practice**, tasks and functionality are usually developed "too" iteratively and (or) there is no time to think through the design. **As a result, the feature makes sense today, and if you expand this feature in a month, you can rewrite the gender of the project.** > *\[[From the discussion](https://t.me/sergeysova/318)]: The developer tries to think 2-3 steps ahead, taking into account future wishes, but here he rests on his own experience* > > *Burns experience engineer usually immediately looking 10 steps ahead, and understand where one feature to divide and combine with the other* > > *But sometimes that comes the task which had to face the experience, and nowhere to take the understanding of how literacy to decompose, with the least unfortunate consequences in the future* ## The role of methodology[​](#the-role-of-methodology "Direct link to heading") **The methodology helps to solve the problems of developers, so that it is easier to solve the problems of users.** There is no solution to the problems of developers only for the sake of developers But in order for the developer to solve his tasks, **you need to understand the user's tasks** - on the contrary, it will not work ### Methodology requirements[​](#methodology-requirements "Direct link to heading") It becomes clear that you need to identify at least two requirements for **Feature-Sliced Design**: 1. The methodology should tell **how to create features, processes and entities** * Which means it should clearly explain *how to divide the code between them*, which means that the naming of these entities should also be laid down in the specification. 2. The methodology should help the architecture **[easily adapt to the changing requirements of the project](/documentation/docs/about/understanding/architecture.md#adaptability)** ## See also[​](#see-also "Direct link to heading") * [(Post) Stimulation for a clear formulation of tasks (+ discussion)](https://t.me/sergeysova/318) > ***The current article** is an adaptation of this discussion, you can read the full uncut version at the link* * [(Discussion) How to break the functionality and what it is](https://t.me/atomicdesign/18972) * [(Article) "How to better organize your applications"](https://alexmngn.medium.com/how-to-better-organize-your-react-applications-2fd3ea1920f1) --- # Signals of architecture WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/194) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > If there is a limitation on the part of the architecture, then there are obvious reasons for this, and consequences if they are ignored > The methodology and architecture gives signals, and how to deal with it depends on what risks you are ready to take on and what is most suitable for your team) ## See also[​](#see-also "Direct link to heading") * [(Thread) About signals from architecture and dataflow](https://t.me/feature_sliced/2070) * [(Thread) About the fundamental nature of architecture](https://t.me/feature_sliced/2492) * [(Thread) About highlighting weak points](https://t.me/feature_sliced/3979) * [(Thread) How to understand that the data model is swollen](https://t.me/feature_sliced/4228) --- # Branding Guidelines FSD's visual identity is based on its core-concepts: `Layered`, `Sliced self-contained parts`, `Parts & Compose`, `Segmented`. But also we tend to design simple, pretty identity, which should convey the FSD philisophy and be easy to recognize. **Please, use FSD's identity "as-is", without changes but with our assets for your comfort.** This brand guide will help you to use FSD's identity correctly. Compatibility FSD had [another legacy identity](https://drive.google.com/drive/folders/11Y-3qZ_C9jOFoW2UbSp11YasOhw4yBdl?usp=sharing) before. Old design didn't represent core-concepts of methodology. Also it was created as pure draft, and should have been actualized. For a compatible and long-term use of the brand, we have been carefully rebranding for a year (2021-2022). **So that you can be sure when using identity of FSD 🍰** *But prefer namely actual identity, not old!* ## Title[​](#title "Direct link to heading") * βœ… **Correct:** `Feature-Sliced Design`, `FSD` * ❌ **Incorrect:** `Feature-Sliced`, `Feature Sliced`, `FeatureSliced`, `feature-sliced`, `feature sliced`, `FS` ## Emojii[​](#emojii "Direct link to heading") The cake 🍰 image represents FSD core concepts quite well, so it has been chosen as our signature emoji > Example: *"🍰 Architectural design methodology for Frontend projects"* ## Logo & Palette[​](#logo--palette "Direct link to heading") FSD has few variations of logo for different context, but it recommended to prefer **primary** | | | | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------- | | Theme | Logo (Ctrl/Cmd + Click for download) | Usage | | primary
(#29BEDC, #517AED) | [![logo-primary](/documentation/img/brand/logo-primary.png)](/documentation/img/brand/logo-primary.png) | Preferred in most cases | | flat
(#3193FF) | [![logo-flat](/documentation/img/brand/logo-flat.png)](/documentation/img/brand/logo-flat.png) | For one-color context | | monochrome
(#FFF) | [![logo-monocrhome](/documentation/img/brand/logo-monochrome.png)](/documentation/img/brand/logo-monochrome.png) | For grayscale context | | square
(#3193FF) | [![logo-square](/documentation/img/brand/logo-square.png)](/documentation/img/brand/logo-square.png) | For square boundaries | ## Banners & Schemes[​](#banners--schemes "Direct link to heading") [![banner-primary](/documentation/img/brand/banner-primary.jpg)](/documentation/img/brand/banner-primary.jpg) [![banner-monochrome](/documentation/img/brand/banner-monochrome.jpg)](/documentation/img/brand/banner-monochrome.jpg) ## Social Preview[​](#social-preview "Direct link to heading") Work in progress... ## Presentation template[​](#presentation-template "Direct link to heading") Work in progress... ## See also[​](#see-also "Direct link to heading") * [Discussion (github)](https://github.com/feature-sliced/documentation/discussions/399) * [History of development with references (figma)](https://www.figma.com/file/RPphccpoeasVB0lMpZwPVR/FSD-Brand?node-id=0%3A1) --- # Decomposition cheatsheet Use this as a quick reference when you're deciding how to decompose your UI. PDF versions are also available below, so you can print it out and keep one under your pillow. ## Choosing a layer[​](#choosing-a-layer "Direct link to heading") [Download PDF](/documentation/assets/files/choosing-a-layer-en-12fdf3265c8fc4f6b58687352b81fce7.pdf) ![Definitions of all layers and self-check questions](/documentation/assets/images/choosing-a-layer-en-5b67f20bb921ba17d78a56c0dc7654a9.jpg) ## Examples[​](#examples "Direct link to heading") ### Tweet[​](#tweet "Direct link to heading") ![decomposed-tweet-bordered-bgLight](/documentation/assets/images/decompose-twitter-7b9a50f879d763c49305b3bf0751ee35.png) ### GitHub[​](#github "Direct link to heading") ![decomposed-github-bordered](/documentation/assets/images/decompose-github-a0eeb839a4b5ef5c480a73726a4451b0.jpg) ## See also[​](#see-also "Direct link to heading") * [(Thread) General logic for features and entities](https://t.me/feature_sliced/4262) * [(Thread) Decomposition of swollen logic](https://t.me/feature_sliced/4210) * [(Thread) About understanding the areas of responsibility during decomposition](https://t.me/feature_sliced/4088) * [(Thread) Decomposition of the Product List widget](https://t.me/feature_sliced/3828) * [(Article) Different approaches to the decomposition of logic](https://www.pluralsight.com/guides/how-to-organize-your-react-+-redux-codebase) * [(Thread) About the difference between features and entities](https://t.me/feature_sliced/3776) * [(Thread) About the difference between things and entities (2)](https://t.me/feature_sliced/3248) * [(Thread) About the application of criteria for decomposition](https://t.me/feature_sliced/3833) --- # FAQ info You can ask your question in our [Telegram chat](https://t.me/feature_sliced), [Discord community](https://discord.gg/S8MzWTUsmp), and [GitHub Discussions](https://github.com/feature-sliced/documentation/discussions). ### Is there a toolkit or a linter?[​](#is-there-a-toolkit-or-a-linter "Direct link to heading") Yes! We have a linter called [Steiger](https://github.com/feature-sliced/steiger) to check your project's architecture and [folder generators](https://github.com/feature-sliced/awesome?tab=readme-ov-file#tools) through a CLI or IDEs. ### Where to store the layout/template of pages?[​](#where-to-store-the-layouttemplate-of-pages "Direct link to heading") If you need plain markup layouts, you can keep them in `shared/ui`. If you need to use higher layers inside, there are a few options: * Perhaps you don't need layouts at all? If the layout is only a few lines, it might be reasonable to duplicate the code in each page rather than try to abstract it. * If you do need layouts, you can have them as separate widgets or pages, and compose them in your router configuration in App. Nested routing is another option. ### What is the difference between a feature and an entity?[​](#what-is-the-difference-between-a-feature-and-an-entity "Direct link to heading") An *entity* is a real-life concept that your app is working with. A *feature* is an interaction that provides real-life value toΒ your app’s users, the thing people want to do with your entities. For more information, along with examples, see the Reference page on [slices](/documentation/docs/reference/layers.md#entities). ### Can I embed pages/features/entities into each other?[​](#can-i-embed-pagesfeaturesentities-into-each-other "Direct link to heading") Yes, but this embedding should happen in higher layers. For example, inside a widget, you can import both features and then insert one feature into another as props/children. You cannot import one feature from another feature, this is prohibited by the [**import rule on layers**](/documentation/docs/reference/layers.md#import-rule-on-layers). ### What about Atomic Design?[​](#what-about-atomic-design "Direct link to heading") The current version of the methodology does not require nor prohibit the use of Atomic Design together with Feature-Sliced Design. For example, Atomic Design [can be applied well](https://t.me/feature_sliced/1653) for the `ui` segment of modules. ### Are there any useful resources/articles/etc. about FSD?[​](#are-there-any-useful-resourcesarticlesetc-about-fsd "Direct link to heading") Yes! ### Why do I need Feature-Sliced Design?[​](#why-do-i-need-feature-sliced-design "Direct link to heading") It helps you and your team to quickly overview the project in terms of its main value-bringing components. A standardized architecture helps to speed up onboarding and resolves debates about code structure. See the [motivation](/documentation/docs/about/motivation.md) page to learn more about why FSD was created. ### Does a novice developer need an architecture/methodology?[​](#does-a-novice-developer-need-an-architecturemethodology "Direct link to heading") Rather yes than no *Usually, when you design and develop a project in one person, everything goes smoothly. But if there are pauses in development, new developers are added to the team - then problems come* ### How do I work with the authorization context?[​](#how-do-i-work-with-the-authorization-context "Direct link to heading") Answered [here](/documentation/docs/guides/examples/auth.md) --- # Overview **Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and stable in the face of ever-changing business requirements. Apart from a set of conventions, FSD is also a toolchain. We have a [linter](https://github.com/feature-sliced/steiger) to check your project's architecture, [folder generators](https://github.com/feature-sliced/awesome?tab=readme-ov-file#tools) through a CLI or IDEs, as well as a rich library of [examples](/documentation/examples.md). ## Is it right for me?[​](#is-it-right-for-me "Direct link to heading") FSD can be implemented in projects and teams of any size. It is right for your project if: * You're doing **frontend** (UI on web, mobile, desktop, etc.) * You're building an **application**, not a library And that's it! There are no restrictions on what programming language, UI framework, or state manager you use. You can also adopt FSD incrementally, use it in monorepos, and scale to great lengths by breaking your app into packages and implementing FSD individually within them. If you already have an architecture and you're considering a switch to FSD, make sure that the current architecture is **causing trouble** in your team. For example, if your project has grown too large and inter-connected to efficiently implement new features, or if you're expecting a lot of new members to join the team. If the current architecture works, maybe it's not worth changing. But if you do decide to migrate, see the [Migration](/documentation/docs/guides/migration/from-custom.md) section for guidance. ## Basic example[​](#basic-example "Direct link to heading") Here is a simple project that implements FSD: * `πŸ“ app` * `πŸ“ pages` * `πŸ“ shared` These top-level folders are called *layers*. Let's look deeper: * `πŸ“‚ app` * `πŸ“ routes` * `πŸ“ analytics` * `πŸ“‚ pages` * `πŸ“ home` * `πŸ“‚ article-reader` * `πŸ“ ui` * `πŸ“ api` * `πŸ“ settings` * `πŸ“‚ shared` * `πŸ“ ui` * `πŸ“ api` Folders inside `πŸ“‚ pages` are called *slices*. They divide the layer by domain (in this case, by pages). Folders inside `πŸ“‚ app`, `πŸ“‚ shared`, and `πŸ“‚ pages/article-reader` are called *segments*, and they divide slices (or layers) by technical purpose, i.e. what the code is for. ## Concepts[​](#concepts "Direct link to heading") Layers, slices, and segments form a hierarchy like this: ![Hierarchy of FSD concepts, described below](/documentation/assets/images/visual_schema-e826067f573946613dcdc76e3f585082.jpg) Pictured above: three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively. The "Layers" pillar contains seven divisions arranged top to bottom and labeled "app", "processes", "pages", "widgets", "features", "entities", and "shared". The "processes" division is crossed out. The "entities" division is connected to the second pillar "Slices" in a way that conveys that the second pillar is the content of "entities". The "Slices" pillar contains three divisions arranged top to bottom and labeled "user", "post", and "comment". The "post" division is connected to the third pillar "Segments" in the same way such that it's the content of "post". The "Segments" pillar contains three divisions, arranged top to bottom and labeled "ui", "model", and "api". ### Layers[​](#layers "Direct link to heading") Layers are standardized across all FSD projects. You don't have to use all of the layers, but their names are important. There are currently seven of them (from top to bottom): 1. **App** β€” everything that makes the app run β€” routing, entrypoints, global styles, providers. 2. **Processes** (deprecated) β€” complex inter-page scenarios. 3. **Pages** β€” full pages or large parts of a page in nested routing. 4. **Widgets** β€” large self-contained chunks of functionality or UI, usually delivering an entire use case. 5. **Features** β€” *reused* implementations of entire product features, i.e. actions that bring business value to the user. 6. **Entities** β€” business entities that the project works with, like `user` or `product`. 7. **Shared** β€” reusable functionality, especially when it's detached from the specifics of the project/business, though not necessarily. warning Layers **App** and **Shared**, unlike other layers, do not have slices and are divided into segments directly. However, all other layers β€” **Entities**, **Features**, **Widgets**, and **Pages**, retain the structure in which you must first create slices, inside which you create the segments. The trick with layers is that modules on one layer can only know about and import from modules from the layers strictly below. ### Slices[​](#slices "Direct link to heading") Next up are slices, which partition the code by business domain. You're free to choose any names for them, and create as many as you wish. Slices make your codebase easier to navigate by keeping logically related modules close together. Slices cannot use other slices on the same layer, and that helps with high cohesion and low coupling. ### Segments[​](#segments "Direct link to heading") Slices, as well as layers App and Shared, consist of segments, and segments group your code by its purpose. Segment names are not constrained by the standard, but there are several conventional names for the most common purposes: * `ui` β€” everything related to UI display: UI components, date formatters, styles, etc. * `api` β€” backend interactions: request functions, data types, mappers, etc. * `model` β€” the data model: schemas, interfaces, stores, and business logic. * `lib` β€” library code that other modules on this slice need. * `config` β€” configuration files and feature flags. Usually these segments are enough for most layers, you would only create your own segments in Shared or App, but this is not a rule. ## Advantages[​](#advantages "Direct link to heading") * **Uniformity**
Since the structure is standardized, projects become more uniform, which makes onboarding new members easier for the team. * **Stability in face of changes and refactoring**
A module on one layer cannot use other modules on the same layer, or the layers above.
This allows you to make isolated modifications without unforeseen consequences to the rest of the app. * **Controlled reuse of logic**
Depending on the layer, you can make code very reusable or very local.
This keeps a balance between following the **DRY** principle and practicality. * **Orientation to business and users needs**
The app is split into business domains and usage of the business language is encouraged in naming, so that you can do useful product work without fully understanding all other unrelated parts of the project. ## Incremental adoption[​](#incremental-adoption "Direct link to heading") If you have an existing codebase that you want to migrate to FSD, we suggest the following strategy. We found it useful in our own migration experience. 1. Start by slowly shaping up the App and Shared layers module-by-module to create a foundation. 2. Distribute all of the existing UI across Widgets and Pages using broad strokes, even if they have dependencies that violate the rules of FSD. 3. Start gradually resolving import violations and also extracting Entities and possibly even Features. It's advised to refrain from adding new large entities while refactoring or refactoring only certain parts of the project. ## Next steps[​](#next-steps "Direct link to heading") * **Want to get a good grasp of how to think in FSD?** Check out the [Tutorial](/documentation/docs/get-started/tutorial.md). * **Prefer to learn from examples?** We have a lot in the [Examples](/documentation/examples.md) section. * **Have questions?** Drop by our [Telegram chat](https://t.me/feature_sliced) and get help from the community. --- # Tutorial ## Part 1. On paper[​](#part-1-on-paper "Direct link to heading") This tutorial will examine the Real World App, also known as Conduit. Conduit is a basic [Medium](https://medium.com/) clone β€” it lets you read and write articles as well as comment on the articles of others. ![Conduit home page](/documentation/assets/images/realworld-feed-anonymous-8cbba45f488931979f6c8da8968ad685.jpg) This is a pretty small application, so we will keep it simple and avoid excessive decomposition. It’s highly likely that the entire app will fit into just three layers: **App**, **Pages**, and **Shared**. If not, we will introduce additional layers as we go. Ready? ### Start by listing the pages[​](#start-by-listing-the-pages "Direct link to heading") If we look at the screenshot above, we can assume at least the following pages: * Home (article feed) * Sign in and sign up * Article reader * Article editor * User profile viewer * User profile editor (user settings) Every one of these pages will become its own *slice* on the Pages *layer*. Recall from the overview that slices are simply folders inside of layers and layers are simply folders with predefined names like `pages`. As such, our Pages folder will look like this: ``` πŸ“‚ pages/ πŸ“ feed/ πŸ“ sign-in/ πŸ“ article-read/ πŸ“ article-edit/ πŸ“ profile/ πŸ“ settings/ ``` The key difference of Feature-Sliced Design from an unregulated code structure is that pages cannot reference each other. That is, one page cannot import code from another page. This is due to the **import rule on layers**: *A module (file) in a slice can only import other slices when they are located on layers strictly below.* In this case, a page is a slice, so modules (files) inside this page can only reference code from layers below, not from the same layer, Pages. ### Close look at the feed[​](#close-look-at-the-feed "Direct link to heading") ![Anonymous user’s perspective](/documentation/assets/images/realworld-feed-anonymous-8cbba45f488931979f6c8da8968ad685.jpg) *Anonymous user’s perspective* ![Authenticated user’s perspective](/documentation/assets/images/realworld-feed-authenticated-15427d9ff7baae009b47b501bee6c059.jpg) *Authenticated user’s perspective* There are three dynamic areas on the feed page: 1. Sign-in links with an indication if you are signed in 2. List of tags that triggers filtering in the feed 3. One/two feeds of articles, each article with a like button The sign-in links are a part of a header that is common to all pages, we will revisit it separately. #### List of tags[​](#list-of-tags "Direct link to heading") To build the list of tags, we need to fetch the available tags, render each tag as a chip, and store the selected tags in a client-side storage. These operations fall into categories β€œAPI interaction”, β€œuser interface”, and β€œstorage”, respectively. In Feature-Sliced Design, code is separated by purpose using *segments*. Segments are folders in slices, and they can have arbitrary names that describe the purpose, but some purposes are so common that there’s a convention for certain segment names: * πŸ“‚Β `api/` for backend interactions * πŸ“‚Β `ui/` for code that handles rendering and appearance * πŸ“‚Β `model/` for storage and business logic * πŸ“‚Β `config/` for feature flags, environment variables and other forms of configuration We will place code that fetches tags into `api`, the tag component into `ui`, and the storage interaction into `model`. #### Articles[​](#articles "Direct link to heading") Using the same grouping principles, we can decompose the feed of articles into the same three segments: * πŸ“‚Β `api/`: fetch paginated articles with like count; like an article * πŸ“‚Β `ui/`: * tab list that can render an extra tab if a tag is selected * individual article * functional pagination * πŸ“‚Β `model/`: client-side storage of the currently loaded articles and current page (if needed) ### Reuse generic code[​](#reuse-generic-code "Direct link to heading") Most pages are very different in intent, but certain things stay the same across the entire app β€” for example, the UI kit that conforms to the design language, or the convention on the backend that everything is done with a REST API with the same authentication method. Since slices are meant to be isolated, code reuse is facilitated by a lower layer, **Shared**. Shared is different from other layers in the sense that it contains segments, not slices. In this way, the Shared layer can be thought of as a hybrid between a layer and a slice. Usually, the code in Shared is not planned ahead of time, but rather extracted during development, because only during development does it become clear which parts of code are actually shared. However, it’s still helpful to keep a mental note of what kind of code naturally belongs in Shared: * πŸ“‚Β `ui/` β€” the UI kit, pure appearance, no business logic. For example, buttons, modal dialogs, form inputs. * πŸ“‚Β `api/` β€” convenience wrappers around request making primitives (like `fetch()` on the Web) and, optionally, functions for triggering particular requests according to the backend specification. * πŸ“‚Β `config/` β€” parsing environment variables * πŸ“‚Β `i18n/` β€” configuration of language support * πŸ“‚Β `router/` β€” routing primitives and route constants Those are just a few examples of segment names in Shared, but you can omit any of them or create your own. The only important thing to remember when creating new segments is that segment names should describe **purpose (the why), not essence (the what)**. Names like β€œcomponents”, β€œhooks”, β€œmodals” *should not* be used because they describe what these files are, but don’t help to navigate the code inside. This requires people on the team to dig through every file in such folders and also keeps unrelated code close, which leads to broad areas of code being affected by refactoring and thus makes code review and testing harder. ### Define a strict public API[​](#define-a-strict-public-api "Direct link to heading") In the context of Feature-Sliced Design, the term *public API* refers to a slice or segment declaring what can be imported from it by other modules in the project. For example, in JavaScript that can be an `index.js` file re-exporting objects from other files in the slice. This enables freedom in refactoring code inside a slice as long as the contract with the outside world (i.e. the public API) stays the same. For the Shared layer that has no slices, it’s usually more convenient to define a separate public API for each segment as opposed to defining one single index of everything in Shared. This keeps imports from Shared naturally organized by intent. For other layers that have slices, the opposite is true β€” it’s usually more practical to define one index per slice and let the slice decide its own set of segments that is unknown to the outside world because other layers usually have a lot less exports. Our slices/segments will appear to each other as follows: ``` πŸ“‚ pages/ πŸ“‚ feed/ πŸ“„ index πŸ“‚ sign-in/ πŸ“„ index πŸ“‚ article-read/ πŸ“„ index πŸ“ … πŸ“‚ shared/ πŸ“‚ ui/ πŸ“„ index πŸ“‚ api/ πŸ“„ index πŸ“ … ``` Whatever is inside folders like `pages/feed` or `shared/ui` is only known to those folders, and other files should not rely on the internal structure of these folders. ### Large reused blocks in the UI[​](#large-reused-blocks-in-the-ui "Direct link to heading") Earlier we made a note to revisit the header that appears on every page. Rebuilding it from scratch on every page would be impractical, so it’s only natural to want to reuse it. We already have Shared to facilitate code reuse, however, there’s a caveat to putting large blocks of UI in Shared β€” the Shared layer is not supposed to know about any of the layers above. Between Shared and Pages there are three other layers: Entities, Features, and Widgets. Some projects may have something in those layers that they need in a large reusable block, and that means we can’t put that reusable block in Shared, or else it would be importing from upper layers, which is prohibited. That’s where the Widgets layer comes in. It is located above Shared, Entities, and Features, so it can use them all. In our case, the header is very simple β€” it’s a static logo and top-level navigation. The navigation needs to make a request to the API to determine if the user is currently logged in or not, but that can be handled by a simple import from the `api` segment. Therefore, we will keep our header in Shared. ### Close look at a page with a form[​](#close-look-at-a-page-with-a-form "Direct link to heading") Let’s also examine a page that’s intended for editing, not reading. For example, the article writer: ![Conduit post editor](/documentation/assets/images/realworld-editor-authenticated-10de4d01479270886859e08592045b1e.jpg) It looks trivial, but contains several aspects of application development that we haven’t explored yet β€” form validation, error states, and data persistence. If we were to build this page, we would grab some inputs and buttons from Shared and put together a form in the `ui` segment of this page. Then, in the `api` segment, we would define a mutation request to create the article on the backend. To validate the request before sending, we need a validation schema, and a good place for it is the `model` segment, since it’s the data model. There we will produce error messages and display them using another component in the `ui` segment. To improve user experience, we could also persist the inputs to prevent accidental data loss. This is also a job of the `model` segment. ### Summary[​](#summary "Direct link to heading") We have examined several pages and outlined a preliminary structure for our application: 1. Shared layer 1. `ui` will contain our reusable UI kit 2. `api` will contain our primitive interactions with the backend 3. The rest will be arranged on demand 2. Pages layer β€” each page is a separate slice 1. `ui` will contain the page itself and all of its parts 2. `api` will contain more specialized data fetching, using `shared/api` 3. `model` might contain client-side storage of the data that we will display Let’s get building! ## Part 2. In code[​](#part-2-in-code "Direct link to heading") Now that we have a plan, let’s put it to practice. We will use React and [Remix](https://remix.run). There's a template ready for this project, clone it from GitHub to get a headstart: . Install dependencies with `npm install` and start the development server with `npm run dev`. Open and you should see a blank app. ### Lay out the pages[​](#lay-out-the-pages "Direct link to heading") Let’s start by creating blank components for all our pages. Run the following command in your project: ``` npx fsd pages feed sign-in article-read article-edit profile settings --segments ui ``` This will create folders like `pages/feed/ui/` and an index file, `pages/feed/index.ts`, for every page. ### Connect the feed page[​](#connect-the-feed-page "Direct link to heading") Let’s connect the root route of our application to the feed page. Create a component, `FeedPage.tsx` in `pages/feed/ui` and put the following inside it: pages/feed/ui/FeedPage.tsx ``` export function FeedPage() { return (

conduit

A place to share your knowledge.

); } ``` Then re-export this component in the feed page’s public API, the `pages/feed/index.ts` file: pages/feed/index.ts ``` export { FeedPage } from "./ui/FeedPage"; ``` Now connect it to the root route. In Remix, routing is file-based, and the route files are located in the `app/routes` folder, which nicely coincides with Feature-Sliced Design. Use the `FeedPage` component in `app/routes/_index.tsx`: app/routes/\_index.tsx ``` import type { MetaFunction } from "@remix-run/node"; import { FeedPage } from "pages/feed"; export const meta: MetaFunction = () => { return [{ title: "Conduit" }]; }; export default FeedPage; ``` Then, if you run the dev server and open the application, you should see the Conduit banner! ![The banner of Conduit](/documentation/assets/images/conduit-banner-a20e38edcd109ee21a8b1426d93a66b3.jpg) ### API client[​](#api-client "Direct link to heading") To talk to the RealWorld backend, let’s create a convenient API client in Shared. Create two segments, `api` for the client and `config` for variables like the backend base URL: ``` npx fsd shared --segments api config ``` Then create `shared/config/backend.ts`: shared/config/backend.ts ``` export { mockBackendUrl as backendBaseUrl } from "mocks/handlers"; ``` shared/config/index.ts ``` export { backendBaseUrl } from "./backend"; ``` Since the RealWorld project conveniently provides an [OpenAPI specification](https://github.com/gothinkster/realworld/blob/main/api/openapi.yml), we can take advantage of auto-generated types for our client. We will use [the `openapi-fetch` package](https://openapi-ts.pages.dev/openapi-fetch/) that comes with an additional type generator. Run the following command to generate up-to-date API typings: ``` npm run generate-api-types ``` This will create a file `shared/api/v1.d.ts`. We will use this file to create a typed API client in `shared/api/client.ts`: shared/api/client.ts ``` import createClient from "openapi-fetch"; import { backendBaseUrl } from "shared/config"; import type { paths } from "./v1"; export const { GET, POST, PUT, DELETE } = createClient({ baseUrl: backendBaseUrl }); ``` shared/api/index.ts ``` export { GET, POST, PUT, DELETE } from "./client"; ``` ### Real data in the feed[​](#real-data-in-the-feed "Direct link to heading") We can now proceed to adding articles to the feed, fetched from the backend. Let’s begin by implementing an article preview component. Create `pages/feed/ui/ArticlePreview.tsx` with the following content: pages/feed/ui/ArticlePreview\.tsx ``` export function ArticlePreview({ article }) { /* TODO */ } ``` Since we’re writing in TypeScript, it would be nice to have a typed article object. If we explore the generated `v1.d.ts`, we can see that the article object is available through `components["schemas"]["Article"]`. So let’s create a file with our data models in Shared and export the models: shared/api/models.ts ``` import type { components } from "./v1"; export type Article = components["schemas"]["Article"]; ``` shared/api/index.ts ``` export { GET, POST, PUT, DELETE } from "./client"; export type { Article } from "./models"; ``` Now we can come back to the article preview component and fill the markup with data. Update the component with the following content: pages/feed/ui/ArticlePreview\.tsx ``` import { Link } from "@remix-run/react"; import type { Article } from "shared/api"; interface ArticlePreviewProps { article: Article; } export function ArticlePreview({ article }: ArticlePreviewProps) { return (
{article.author.username} {new Date(article.createdAt).toLocaleDateString(undefined, { dateStyle: "long", })}

{article.title}

{article.description}

Read more...
    {article.tagList.map((tag) => (
  • {tag}
  • ))}
); } ``` The like button doesn’t do anything for now, we will fix that when we get to the article reader page and implement the liking functionality. Now we can fetch the articles and render out a bunch of these cards. Fetching data in Remix is done with *loaders* β€” server-side functions that fetch exactly what a page needs. Loaders interact with the API on the page’s behalf, so we will put them in the `api` segment of a page: pages/feed/api/loader.ts ``` import { json } from "@remix-run/node"; import { GET } from "shared/api"; export const loader = async () => { const { data: articles, error, response } = await GET("/articles"); if (error !== undefined) { throw json(error, { status: response.status }); } return json({ articles }); }; ``` To connect it to the page, we need to export it with the name `loader` from the route file: pages/feed/index.ts ``` export { FeedPage } from "./ui/FeedPage"; export { loader } from "./api/loader"; ``` app/routes/\_index.tsx ``` import type { MetaFunction } from "@remix-run/node"; import { FeedPage } from "pages/feed"; export { loader } from "pages/feed"; export const meta: MetaFunction = () => { return [{ title: "Conduit" }]; }; export default FeedPage; ``` And the final step is to render these cards in the feed. Update your `FeedPage` with the following code: pages/feed/ui/FeedPage.tsx ``` import { useLoaderData } from "@remix-run/react"; import type { loader } from "../api/loader"; import { ArticlePreview } from "./ArticlePreview"; export function FeedPage() { const { articles } = useLoaderData(); return (

conduit

A place to share your knowledge.

{articles.articles.map((article) => ( ))}
); } ``` ### Filtering by tag[​](#filtering-by-tag "Direct link to heading") Regarding the tags, our job is to fetch them from the backend and to store the currently selected tag. We already know how to do fetching β€” it’s another request from the loader. We will use a convenience function `promiseHash` from a package `remix-utils`, which is already installed. Update the loader file, `pages/feed/api/loader.ts`, with the following code: pages/feed/api/loader.ts ``` import { json } from "@remix-run/node"; import type { FetchResponse } from "openapi-fetch"; import { promiseHash } from "remix-utils/promise"; import { GET } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { const { data, error, response } = await responsePromise; if (error !== undefined) { throw json(error, { status: response.status }); } return data as NonNullable; } export const loader = async () => { return json( await promiseHash({ articles: throwAnyErrors(GET("/articles")), tags: throwAnyErrors(GET("/tags")), }), ); }; ``` You might notice that we extracted the error handling into a generic function `throwAnyErrors`. It looks pretty useful, so we might want to reuse it later, but for now let’s just keep an eye on it. Now, to the list of tags. It needs to be interactive β€” clicking on a tag should make that tag selected. By Remix convention, we will use the URL search parameters as our storage for the selected tag. Let the browser take care of storage while we focus on more important things. Update `pages/feed/ui/FeedPage.tsx` with the following code: pages/feed/ui/FeedPage.tsx ``` import { Form, useLoaderData } from "@remix-run/react"; import { ExistingSearchParams } from "remix-utils/existing-search-params"; import type { loader } from "../api/loader"; import { ArticlePreview } from "./ArticlePreview"; export function FeedPage() { const { articles, tags } = useLoaderData(); return (

conduit

A place to share your knowledge.

{articles.articles.map((article) => ( ))}

Popular Tags

{tags.tags.map((tag) => ( ))}
); } ``` Then we need to use the `tag` search parameter in our loader. Change the `loader` function in `pages/feed/api/loader.ts` to the following: pages/feed/api/loader.ts ``` import { json, type LoaderFunctionArgs } from "@remix-run/node"; import type { FetchResponse } from "openapi-fetch"; import { promiseHash } from "remix-utils/promise"; import { GET } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { const { data, error, response } = await responsePromise; if (error !== undefined) { throw json(error, { status: response.status }); } return data as NonNullable; } export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url); const selectedTag = url.searchParams.get("tag") ?? undefined; return json( await promiseHash({ articles: throwAnyErrors( GET("/articles", { params: { query: { tag: selectedTag } } }), ), tags: throwAnyErrors(GET("/tags")), }), ); }; ``` That’s it, no `model` segment necessary. Remix is pretty neat. ### Pagination[​](#pagination "Direct link to heading") In a similar fashion, we can implement the pagination. Feel free to give it a shot yourself or just copy the code below. There’s no one to judge you anyway. pages/feed/api/loader.ts ``` import { json, type LoaderFunctionArgs } from "@remix-run/node"; import type { FetchResponse } from "openapi-fetch"; import { promiseHash } from "remix-utils/promise"; import { GET } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { const { data, error, response } = await responsePromise; if (error !== undefined) { throw json(error, { status: response.status }); } return data as NonNullable; } /** Amount of articles on one page. */ export const LIMIT = 20; export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url); const selectedTag = url.searchParams.get("tag") ?? undefined; const page = parseInt(url.searchParams.get("page") ?? "", 10); return json( await promiseHash({ articles: throwAnyErrors( GET("/articles", { params: { query: { tag: selectedTag, limit: LIMIT, offset: !Number.isNaN(page) ? page * LIMIT : undefined, }, }, }), ), tags: throwAnyErrors(GET("/tags")), }), ); }; ``` pages/feed/ui/FeedPage.tsx ``` import { Form, useLoaderData, useSearchParams } from "@remix-run/react"; import { ExistingSearchParams } from "remix-utils/existing-search-params"; import { LIMIT, type loader } from "../api/loader"; import { ArticlePreview } from "./ArticlePreview"; export function FeedPage() { const [searchParams] = useSearchParams(); const { articles, tags } = useLoaderData(); const pageAmount = Math.ceil(articles.articlesCount / LIMIT); const currentPage = parseInt(searchParams.get("page") ?? "1", 10); return (

conduit

A place to share your knowledge.

{articles.articles.map((article) => ( ))}
    {Array(pageAmount) .fill(null) .map((_, index) => index + 1 === currentPage ? (
  • {index + 1}
  • ) : (
  • ), )}

Popular Tags

{tags.tags.map((tag) => ( ))}
); } ``` So that’s also done. There’s also the tab list that can be similarly implemented, but let’s hold on to that until we implement authentication. Speaking of which! ### Authentication[​](#authentication "Direct link to heading") Authentication involves two pages β€” one to login and another to register. They are mostly the same, so it makes sense to keep them in the same slice, `sign-in`, so that they can reuse code if needed. Create `RegisterPage.tsx` in the `ui` segment of `pages/sign-in` with the following content: pages/sign-in/ui/RegisterPage.tsx ``` import { Form, Link, useActionData } from "@remix-run/react"; import type { register } from "../api/register"; export function RegisterPage() { const registerData = useActionData(); return (

Sign up

Have an account?

{registerData?.error && (
    {registerData.error.errors.body.map((error) => (
  • {error}
  • ))}
)}
); } ``` We have a broken import to fix now. It involves a new segment, so create that: ``` npx fsd pages sign-in -s api ``` However, before we can implement the backend part of registering, we need some infrastructure code for Remix to handle sessions. That goes to Shared, in case any other page needs it. Put the following code in `shared/api/auth.server.ts`. This is highly Remix-specific, so don’t worry too much about it, just copy-paste: shared/api/auth.server.ts ``` import { createCookieSessionStorage, redirect } from "@remix-run/node"; import invariant from "tiny-invariant"; import type { User } from "./models"; invariant( process.env.SESSION_SECRET, "SESSION_SECRET must be set for authentication to work", ); const sessionStorage = createCookieSessionStorage<{ user: User; }>({ cookie: { name: "__session", httpOnly: true, path: "/", sameSite: "lax", secrets: [process.env.SESSION_SECRET], secure: process.env.NODE_ENV === "production", }, }); export async function createUserSession({ request, user, redirectTo, }: { request: Request; user: User; redirectTo: string; }) { const cookie = request.headers.get("Cookie"); const session = await sessionStorage.getSession(cookie); session.set("user", user); return redirect(redirectTo, { headers: { "Set-Cookie": await sessionStorage.commitSession(session, { maxAge: 60 * 60 * 24 * 7, // 7 days }), }, }); } export async function getUserFromSession(request: Request) { const cookie = request.headers.get("Cookie"); const session = await sessionStorage.getSession(cookie); return session.get("user") ?? null; } export async function requireUser(request: Request) { const user = await getUserFromSession(request); if (user === null) { throw redirect("/login"); } return user; } ``` And also export the `User` model from the `models.ts` file right next to it: shared/api/models.ts ``` import type { components } from "./v1"; export type Article = components["schemas"]["Article"]; export type User = components["schemas"]["User"]; ``` Before this code can work, the `SESSION_SECRET` environment variable needs to be set. Create a file called `.env` in the root of the project, write `SESSION_SECRET=` and then mash some keys on your keyboard to create a long random string. You should get something like this: .env ``` SESSION_SECRET=dontyoudarecopypastethis ``` Finally, add some exports to the public API to make use of this code: shared/api/index.ts ``` export { GET, POST, PUT, DELETE } from "./client"; export type { Article } from "./models"; export { createUserSession, getUserFromSession, requireUser } from "./auth.server"; ``` Now we can write the code that will talk to the RealWorld backend to actually do the registration. We will keep that in `pages/sign-in/api`. Create a file called `register.ts` and put the following code inside: pages/sign-in/api/register.ts ``` import { json, type ActionFunctionArgs } from "@remix-run/node"; import { POST, createUserSession } from "shared/api"; export const register = async ({ request }: ActionFunctionArgs) => { const formData = await request.formData(); const username = formData.get("username")?.toString() ?? ""; const email = formData.get("email")?.toString() ?? ""; const password = formData.get("password")?.toString() ?? ""; const { data, error } = await POST("/users", { body: { user: { email, password, username } }, }); if (error) { return json({ error }, { status: 400 }); } else { return createUserSession({ request: request, user: data.user, redirectTo: "/", }); } }; ``` pages/sign-in/index.ts ``` export { RegisterPage } from './ui/RegisterPage'; export { register } from './api/register'; ``` Almost done! Just need to connect the page and action to the `/register` route. Create `register.tsx` in `app/routes`: app/routes/register.tsx ``` import { RegisterPage, register } from "pages/sign-in"; export { register as action }; export default RegisterPage; ``` Now if you go to , you should be able to create a user! The rest of the application won’t react to this yet, we’ll address that momentarily. In a very similar way, we can implement the login page. Give it a try or just grab the code and move on: pages/sign-in/api/sign-in.ts ``` import { json, type ActionFunctionArgs } from "@remix-run/node"; import { POST, createUserSession } from "shared/api"; export const signIn = async ({ request }: ActionFunctionArgs) => { const formData = await request.formData(); const email = formData.get("email")?.toString() ?? ""; const password = formData.get("password")?.toString() ?? ""; const { data, error } = await POST("/users/login", { body: { user: { email, password } }, }); if (error) { return json({ error }, { status: 400 }); } else { return createUserSession({ request: request, user: data.user, redirectTo: "/", }); } }; ``` pages/sign-in/ui/SignInPage.tsx ``` import { Form, Link, useActionData } from "@remix-run/react"; import type { signIn } from "../api/sign-in"; export function SignInPage() { const signInData = useActionData(); return (

Sign in

Need an account?

{signInData?.error && (
    {signInData.error.errors.body.map((error) => (
  • {error}
  • ))}
)}
); } ``` pages/sign-in/index.ts ``` export { RegisterPage } from './ui/RegisterPage'; export { register } from './api/register'; export { SignInPage } from './ui/SignInPage'; export { signIn } from './api/sign-in'; ``` app/routes/login.tsx ``` import { SignInPage, signIn } from "pages/sign-in"; export { signIn as action }; export default SignInPage; ``` Now let’s give the users a way to actually get to these pages. ### Header[​](#header "Direct link to heading") As we discussed in part 1, the app header is commonly placed either in Widgets or in Shared. We will put it in Shared because it’s very simple and all the business logic can be kept outside of it. Let’s create a place for it: ``` npx fsd shared ui ``` Now create `shared/ui/Header.tsx` with the following contents: shared/ui/Header.tsx ``` import { useContext } from "react"; import { Link, useLocation } from "@remix-run/react"; import { CurrentUser } from "../api/currentUser"; export function Header() { const currentUser = useContext(CurrentUser); const { pathname } = useLocation(); return ( ); } ``` Export this component from `shared/ui`: shared/ui/index.ts ``` export { Header } from "./Header"; ``` In the header, we rely on the context that’s kept in `shared/api`. Create that as well: shared/api/currentUser.ts ``` import { createContext } from "react"; import type { User } from "./models"; export const CurrentUser = createContext(null); ``` shared/api/index.ts ``` export { GET, POST, PUT, DELETE } from "./client"; export type { Article } from "./models"; export { createUserSession, getUserFromSession, requireUser } from "./auth.server"; export { CurrentUser } from "./currentUser"; ``` Now let’s add the header to the page. We want it to be on every single page, so it makes sense to simply add it to the root route and wrap the outlet (the place where the page will be rendered) with the `CurrentUser` context provider. This way our entire app and also the header has access to the current user object. We will also add a loader to actually obtain the current user object from cookies. Drop the following into `app/root.tsx`: app/root.tsx ``` import { cssBundleHref } from "@remix-run/css-bundle"; import type { LinksFunction, LoaderFunctionArgs } from "@remix-run/node"; import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, } from "@remix-run/react"; import { Header } from "shared/ui"; import { getUserFromSession, CurrentUser } from "shared/api"; export const links: LinksFunction = () => [ ...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []), ]; export const loader = ({ request }: LoaderFunctionArgs) => getUserFromSession(request); export default function App() { const user = useLoaderData(); return (
); } ``` At this point, you should end up with the following on the home page: ![The feed page of Conduit, including the header, the feed, and the tags. The tabs are still missing.](/documentation/assets/images/realworld-feed-without-tabs-5da4c9072101ac20e82e2234bd3badbe.jpg) The feed page of Conduit, including the header, the feed, and the tags. The tabs are still missing. ### Tabs[​](#tabs "Direct link to heading") Now that we can detect the authentication state, let’s also quickly implement the tabs and post likes to be done with the feed page. We need another form, but this page file is getting kind of large, so let’s move these forms into adjacent files. We will create `Tabs.tsx`, `PopularTags.tsx`, and `Pagination.tsx` with the following content: pages/feed/ui/Tabs.tsx ``` import { useContext } from "react"; import { Form, useSearchParams } from "@remix-run/react"; import { CurrentUser } from "shared/api"; export function Tabs() { const [searchParams] = useSearchParams(); const currentUser = useContext(CurrentUser); return (
    {currentUser !== null && (
  • )}
  • {searchParams.has("tag") && (
  • {searchParams.get("tag")}
  • )}
); } ``` pages/feed/ui/PopularTags.tsx ``` import { Form, useLoaderData } from "@remix-run/react"; import { ExistingSearchParams } from "remix-utils/existing-search-params"; import type { loader } from "../api/loader"; export function PopularTags() { const { tags } = useLoaderData(); return (

Popular Tags

{tags.tags.map((tag) => ( ))}
); } ``` pages/feed/ui/Pagination.tsx ``` import { Form, useLoaderData, useSearchParams } from "@remix-run/react"; import { ExistingSearchParams } from "remix-utils/existing-search-params"; import { LIMIT, type loader } from "../api/loader"; export function Pagination() { const [searchParams] = useSearchParams(); const { articles } = useLoaderData(); const pageAmount = Math.ceil(articles.articlesCount / LIMIT); const currentPage = parseInt(searchParams.get("page") ?? "1", 10); return (
    {Array(pageAmount) .fill(null) .map((_, index) => index + 1 === currentPage ? (
  • {index + 1}
  • ) : (
  • ), )}
); } ``` And now we can significantly simplify the feed page itself: pages/feed/ui/FeedPage.tsx ``` import { useLoaderData } from "@remix-run/react"; import type { loader } from "../api/loader"; import { ArticlePreview } from "./ArticlePreview"; import { Tabs } from "./Tabs"; import { PopularTags } from "./PopularTags"; import { Pagination } from "./Pagination"; export function FeedPage() { const { articles } = useLoaderData(); return (

conduit

A place to share your knowledge.

{articles.articles.map((article) => ( ))}
); } ``` We also need to account for the new tab in the loader function: pages/feed/api/loader.ts ``` import { json, type LoaderFunctionArgs } from "@remix-run/node"; import type { FetchResponse } from "openapi-fetch"; import { promiseHash } from "remix-utils/promise"; import { GET, requireUser } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { /* unchanged */ } /** Amount of articles on one page. */ export const LIMIT = 20; export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url); const selectedTag = url.searchParams.get("tag") ?? undefined; const page = parseInt(url.searchParams.get("page") ?? "", 10); if (url.searchParams.get("source") === "my-feed") { const userSession = await requireUser(request); return json( await promiseHash({ articles: throwAnyErrors( GET("/articles/feed", { params: { query: { limit: LIMIT, offset: !Number.isNaN(page) ? page * LIMIT : undefined, }, }, headers: { Authorization: `Token ${userSession.token}` }, }), ), tags: throwAnyErrors(GET("/tags")), }), ); } return json( await promiseHash({ articles: throwAnyErrors( GET("/articles", { params: { query: { tag: selectedTag, limit: LIMIT, offset: !Number.isNaN(page) ? page * LIMIT : undefined, }, }, }), ), tags: throwAnyErrors(GET("/tags")), }), ); }; ``` Before we leave the feed page, let’s add some code that handles likes to posts. Change your `ArticlePreview.tsx` to the following: pages/feed/ui/ArticlePreview\.tsx ``` import { Form, Link } from "@remix-run/react"; import type { Article } from "shared/api"; interface ArticlePreviewProps { article: Article; } export function ArticlePreview({ article }: ArticlePreviewProps) { return (
{article.author.username} {new Date(article.createdAt).toLocaleDateString(undefined, { dateStyle: "long", })}

{article.title}

{article.description}

Read more...
    {article.tagList.map((tag) => (
  • {tag}
  • ))}
); } ``` This code will send a POST request to `/article/:slug` with `_action=favorite` to mark the article as favorite. It won’t work yet, but as we start working on the article reader, we will implement this too. And with that we are officially done with the feed! Yay! ### Article reader[​](#article-reader "Direct link to heading") First, we need data. Let’s create a loader: ``` npx fsd pages article-read -s api ``` pages/article-read/api/loader.ts ``` import { json, type LoaderFunctionArgs } from "@remix-run/node"; import invariant from "tiny-invariant"; import type { FetchResponse } from "openapi-fetch"; import { promiseHash } from "remix-utils/promise"; import { GET, getUserFromSession } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { const { data, error, response } = await responsePromise; if (error !== undefined) { throw json(error, { status: response.status }); } return data as NonNullable; } export const loader = async ({ request, params }: LoaderFunctionArgs) => { invariant(params.slug, "Expected a slug parameter"); const currentUser = await getUserFromSession(request); const authorization = currentUser ? { Authorization: `Token ${currentUser.token}` } : undefined; return json( await promiseHash({ article: throwAnyErrors( GET("/articles/{slug}", { params: { path: { slug: params.slug }, }, headers: authorization, }), ), comments: throwAnyErrors( GET("/articles/{slug}/comments", { params: { path: { slug: params.slug }, }, headers: authorization, }), ), }), ); }; ``` pages/article-read/index.ts ``` export { loader } from "./api/loader"; ``` Now we can connect it to the route `/article/:slug` by creating the a route file called `article.$slug.tsx`: app/routes/article.$slug.tsx ``` export { loader } from "pages/article-read"; ``` The page itself consists of three main blocks β€” the article header with actions (repeated twice), the article body, and the comments section. This is the markup for the page, it’s not particularly interesting: pages/article-read/ui/ArticleReadPage.tsx ``` import { useLoaderData } from "@remix-run/react"; import type { loader } from "../api/loader"; import { ArticleMeta } from "./ArticleMeta"; import { Comments } from "./Comments"; export function ArticleReadPage() { const { article } = useLoaderData(); return (

{article.article.title}

{article.article.body}

    {article.article.tagList.map((tag) => (
  • {tag}
  • ))}

); } ``` What’s more interesting is the `ArticleMeta` and `Comments`. They contain write operations such as liking an article, leaving a comment, etc. To get them to work, we first need to implement the backend part. Create `action.ts` in the `api` segment of the page: pages/article-read/api/action.ts ``` import { redirect, type ActionFunctionArgs } from "@remix-run/node"; import { namedAction } from "remix-utils/named-action"; import { redirectBack } from "remix-utils/redirect-back"; import invariant from "tiny-invariant"; import { DELETE, POST, requireUser } from "shared/api"; export const action = async ({ request, params }: ActionFunctionArgs) => { const currentUser = await requireUser(request); const authorization = { Authorization: `Token ${currentUser.token}` }; const formData = await request.formData(); return namedAction(formData, { async delete() { invariant(params.slug, "Expected a slug parameter"); await DELETE("/articles/{slug}", { params: { path: { slug: params.slug } }, headers: authorization, }); return redirect("/"); }, async favorite() { invariant(params.slug, "Expected a slug parameter"); await POST("/articles/{slug}/favorite", { params: { path: { slug: params.slug } }, headers: authorization, }); return redirectBack(request, { fallback: "/" }); }, async unfavorite() { invariant(params.slug, "Expected a slug parameter"); await DELETE("/articles/{slug}/favorite", { params: { path: { slug: params.slug } }, headers: authorization, }); return redirectBack(request, { fallback: "/" }); }, async createComment() { invariant(params.slug, "Expected a slug parameter"); const comment = formData.get("comment"); invariant(typeof comment === "string", "Expected a comment parameter"); await POST("/articles/{slug}/comments", { params: { path: { slug: params.slug } }, headers: { ...authorization, "Content-Type": "application/json" }, body: { comment: { body: comment } }, }); return redirectBack(request, { fallback: "/" }); }, async deleteComment() { invariant(params.slug, "Expected a slug parameter"); const commentId = formData.get("id"); invariant(typeof commentId === "string", "Expected an id parameter"); const commentIdNumeric = parseInt(commentId, 10); invariant( !Number.isNaN(commentIdNumeric), "Expected a numeric id parameter", ); await DELETE("/articles/{slug}/comments/{id}", { params: { path: { slug: params.slug, id: commentIdNumeric } }, headers: authorization, }); return redirectBack(request, { fallback: "/" }); }, async followAuthor() { const authorUsername = formData.get("username"); invariant( typeof authorUsername === "string", "Expected a username parameter", ); await POST("/profiles/{username}/follow", { params: { path: { username: authorUsername } }, headers: authorization, }); return redirectBack(request, { fallback: "/" }); }, async unfollowAuthor() { const authorUsername = formData.get("username"); invariant( typeof authorUsername === "string", "Expected a username parameter", ); await DELETE("/profiles/{username}/follow", { params: { path: { username: authorUsername } }, headers: authorization, }); return redirectBack(request, { fallback: "/" }); }, }); }; ``` Export that from the slice and then from the route. While we’re at it, let’s also connect the page itself: pages/article-read/index.ts ``` export { ArticleReadPage } from "./ui/ArticleReadPage"; export { loader } from "./api/loader"; export { action } from "./api/action"; ``` app/routes/article.$slug.tsx ``` import { ArticleReadPage } from "pages/article-read"; export { loader, action } from "pages/article-read"; export default ArticleReadPage; ``` Now, even though we haven’t implemented the like button on the reader page yet, the like button in the feed will start working! That’s because it’s been sending β€œlike” requests to this route. Give that a try. `ArticleMeta` and `Comments` are, again, a bunch of forms. We’ve done this before, let’s grab their code and move on: pages/article-read/ui/ArticleMeta.tsx ``` import { Form, Link, useLoaderData } from "@remix-run/react"; import { useContext } from "react"; import { CurrentUser } from "shared/api"; import type { loader } from "../api/loader"; export function ArticleMeta() { const currentUser = useContext(CurrentUser); const { article } = useLoaderData(); return (
{article.article.author.username} {article.article.createdAt}
{article.article.author.username == currentUser?.username ? ( <> Edit Article    ) : ( <>    )}
); } ``` pages/article-read/ui/Comments.tsx ``` import { useContext } from "react"; import { Form, Link, useLoaderData } from "@remix-run/react"; import { CurrentUser } from "shared/api"; import type { loader } from "../api/loader"; export function Comments() { const { comments } = useLoaderData(); const currentUser = useContext(CurrentUser); return (
{currentUser !== null ? (
) : (

Sign in   or   Sign up   to add comments on this article.

)} {comments.comments.map((comment) => (

{comment.body}

  {comment.author.username} {comment.createdAt} {comment.author.username === currentUser?.username && (
)}
))}
); } ``` And with that our article reader is also complete! The buttons to follow the author, like a post, and leave a comment should now function as expected. ![Article reader with functioning buttons to like and follow](/documentation/assets/images/realworld-article-reader-6a420e4f2afe139d2bdd54d62974f0b9.jpg) Article reader with functioning buttons to like and follow ### Article editor[​](#article-editor "Direct link to heading") This is the last page that we will cover in this tutorial, and the most interesting part here is how we’re going to validate form data. The page itself, `article-edit/ui/ArticleEditPage.tsx`, will be quite simple, extra complexity stowed away into two other components: pages/article-edit/ui/ArticleEditPage.tsx ``` import { Form, useLoaderData } from "@remix-run/react"; import type { loader } from "../api/loader"; import { TagsInput } from "./TagsInput"; import { FormErrors } from "./FormErrors"; export function ArticleEditPage() { const article = useLoaderData(); return (
); } ``` This page gets the current article (unless we’re writing from scratch) and fills in the corresponding form fields. We’ve seen this before. The interesting part is `FormErrors`, because it will receive the validation result and display it to the user. Let’s take a look: pages/article-edit/ui/FormErrors.tsx ``` import { useActionData } from "@remix-run/react"; import type { action } from "../api/action"; export function FormErrors() { const actionData = useActionData(); return actionData?.errors != null ? (
    {actionData.errors.map((error) => (
  • {error}
  • ))}
) : null; } ``` Here we are assuming that our action will return the `errors` field, an array of human-readable error messages. We will get to the action shortly. Another component is the tags input. It’s just a plain input field with an additional preview of chosen tags. Not much to see here: pages/article-edit/ui/TagsInput.tsx ``` import { useEffect, useRef, useState } from "react"; export function TagsInput({ name, defaultValue, }: { name: string; defaultValue?: Array; }) { const [tagListState, setTagListState] = useState(defaultValue ?? []); function removeTag(tag: string): void { const newTagList = tagListState.filter((t) => t !== tag); setTagListState(newTagList); } const tagsInput = useRef(null); useEffect(() => { tagsInput.current && (tagsInput.current.value = tagListState.join(",")); }, [tagListState]); return ( <> setTagListState(e.target.value.split(",").filter(Boolean)) } />
{tagListState.map((tag) => ( [" ", "Enter"].includes(e.key) && removeTag(tag) } onClick={() => removeTag(tag)} >{" "} {tag} ))}
); } ``` Now, for the API part. The loader should look at the URL, and if it contains an article slug, that means we’re editing an existing article, and its data should be loaded. Otherwise, return nothing. Let’s create that loader: pages/article-edit/api/loader.ts ``` import { json, type LoaderFunctionArgs } from "@remix-run/node"; import type { FetchResponse } from "openapi-fetch"; import { GET, requireUser } from "shared/api"; async function throwAnyErrors( responsePromise: Promise>, ) { const { data, error, response } = await responsePromise; if (error !== undefined) { throw json(error, { status: response.status }); } return data as NonNullable; } export const loader = async ({ params, request }: LoaderFunctionArgs) => { const currentUser = await requireUser(request); if (!params.slug) { return { article: null }; } return throwAnyErrors( GET("/articles/{slug}", { params: { path: { slug: params.slug } }, headers: { Authorization: `Token ${currentUser.token}` }, }), ); }; ``` The action will take the new field values, run them through our data schema, and if everything is correct, commit those changes to the backend, either by updating an existing article or creating a new one: pages/article-edit/api/action.ts ``` import { json, redirect, type ActionFunctionArgs } from "@remix-run/node"; import { POST, PUT, requireUser } from "shared/api"; import { parseAsArticle } from "../model/parseAsArticle"; export const action = async ({ request, params }: ActionFunctionArgs) => { try { const { body, description, title, tags } = parseAsArticle( await request.formData(), ); const tagList = tags?.split(",") ?? []; const currentUser = await requireUser(request); const payload = { body: { article: { title, description, body, tagList, }, }, headers: { Authorization: `Token ${currentUser.token}` }, }; const { data, error } = await (params.slug ? PUT("/articles/{slug}", { params: { path: { slug: params.slug } }, ...payload, }) : POST("/articles", payload)); if (error) { return json({ errors: error }, { status: 422 }); } return redirect(`/article/${data.article.slug ?? ""}`); } catch (errors) { return json({ errors }, { status: 400 }); } }; ``` The schema doubles as a parsing function for `FormData`, which allows us to conveniently get the clean fields or just throw the errors to handle at the end. Here’s how that parsing function could look: pages/article-edit/model/parseAsArticle.ts ``` export function parseAsArticle(data: FormData) { const errors = []; const title = data.get("title"); if (typeof title !== "string" || title === "") { errors.push("Give this article a title"); } const description = data.get("description"); if (typeof description !== "string" || description === "") { errors.push("Describe what this article is about"); } const body = data.get("body"); if (typeof body !== "string" || body === "") { errors.push("Write the article itself"); } const tags = data.get("tags"); if (typeof tags !== "string") { errors.push("The tags must be a string"); } if (errors.length > 0) { throw errors; } return { title, description, body, tags: data.get("tags") ?? "" } as { title: string; description: string; body: string; tags: string; }; } ``` Arguably, it’s a bit lengthy and repetitive, but that’s the price we pay for human-readable errors. This could also be a Zod schema, for example, but then we would have to render error messages on the frontend, and this form is not worth the complication. One last step β€” connect the page, the loader, and the action to the routes. Since we neatly support both creation and editing, we can export the same thing from both `editor._index.tsx` and `editor.$slug.tsx`: pages/article-edit/index.ts ``` export { ArticleEditPage } from "./ui/ArticleEditPage"; export { loader } from "./api/loader"; export { action } from "./api/action"; ``` app/routes/editor.\_index.tsx, app/routes/editor.$slug.tsx (same content) ``` import { ArticleEditPage } from "pages/article-edit"; export { loader, action } from "pages/article-edit"; export default ArticleEditPage; ``` We’re done now! Log in and try creating a new article. Or β€œforget” to write the article and see the validation kick in. ![The Conduit article editor, with the title field saying β€œNew article” and the rest of the fields empty. Above the form there are two errors: β€œDescribe what this article is about” and β€œWrite the article itself”.](/documentation/assets/images/realworld-article-editor-bc3ee45c96ae905fdbb54d6463d12723.jpg) The Conduit article editor, with the title field saying β€œNew article” and the rest of the fields empty. Above the form there are two errors: **β€œDescribe what this article is about”** and **β€œWrite the article itself”**. The profile and settings pages are very similar to the article reader and editor, they are left as an exercise for the reader, that’s you :) --- # Handling API Requests ## Shared API Requests[​](#shared-api-requests "Direct link to heading") Start by placing common API request logic in the `shared/api` directory. This makes it easy to reuse requests across your application and helps with faster prototyping. For many projects, this is all you'll need for API calls. A typical file structure would be: * πŸ“‚ shared * πŸ“‚ api * πŸ“„ client.ts * πŸ“„ index.ts * πŸ“‚ endpoints * πŸ“„ login.ts The `client.ts` file centralizes your HTTP request setup. It wraps your chosen method (like `fetch()` or an `axios` instance) and handles common configurations, such as: * Backend base URL. * Default headers (e.g., for authentication). * Data serialization. Here are examples for `axios` and `fetch`: * Axios * Fetch shared/api/client.ts ``` // Example using axios import axios from 'axios'; export const client = axios.create({ baseURL: 'https://your-api-domain.com/api/', timeout: 5000, headers: { 'X-Custom-Header': 'my-custom-value' } }); ``` shared/api/client.ts ``` export const client = { async post(endpoint: string, body: any, options?: RequestInit) { const response = await fetch(`https://your-api-domain.com/api${endpoint}`, { method: 'POST', body: JSON.stringify(body), ...options, headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'my-custom-value', ...options?.headers, }, }); return response.json(); } // ... other methods like put, delete, etc. }; ``` Organize your individual API request functions in `shared/api/endpoints`, grouping them by the API endpoint. note To keep examples focused, we omit form interaction and validation. For details on libraries like Zod or Valibot, refer to the [Type Validation and Schemas](/documentation/docs/guides/examples/types.md#type-validation-schemas-and-zod) article. shared/api/endpoints/login.ts ``` import { client } from '../client'; export interface LoginCredentials { email: string; password: string; } export function login(credentials: LoginCredentials) { return client.post('/login', credentials); } ``` Use an `index.ts` file in `shared/api` to export your request functions. shared/api/index.ts ``` export { client } from './client'; // If you want to export the client itself export { login } from './endpoints/login'; export type { LoginCredentials } from './endpoints/login'; ``` ## Slice-Specific API Requests[​](#slice-specific-api-requests "Direct link to heading") If an API request is only used by a specific slice (like a single page or feature) and won't be reused, place it in the api segment of that slice. This keeps slice-specific logic neatly contained. * πŸ“‚ pages * πŸ“‚ login * πŸ“„ index.ts * πŸ“‚ api * πŸ“„ login.ts * πŸ“‚ ui * πŸ“„ LoginPage.tsx pages/login/api/login.ts ``` import { client } from 'shared/api'; interface LoginCredentials { email: string; password: string; } export function login(credentials: LoginCredentials) { return client.post('/login', credentials); } ``` You don't need to export `login()` function in the page's public API, because it's unlikely that any other place in the app will need this request. note Avoid placing API calls and response types in the `entities` layer prematurely. Backend responses may differ from what your frontend entities need. API logic in `shared/api` or a slice's `api` segment allows you to transform data appropriately, keeping entities focused on frontend concerns. ## Using Client Generators[​](#client-generators "Direct link to heading") If your backend has an OpenAPI specification, tools like [orval](https://orval.dev/) or [openapi-typescript](https://openapi-ts.dev/) can generate API types and request functions for you. Place the generated code in, for example, `shared/api/openapi`. Make sure to include `README.md` to document what those types are, and how to generate them. ## Integrating with Server State Libraries[​](#server-state-libraries "Direct link to heading") When using server state libraries like [TanStack Query (React Query)](https://tanstack.com/query/latest) or [Pinia Colada](https://pinia-colada.esm.dev/) you might need to share types or cache keys between slices. Use the `shared` layer for things like: * API data types * Cache keys * Common query/mutation options For more details on how to work with server state libraries, refer to [React Query article](/documentation/docs/guides/tech/with-react-query.md) --- # Authentication Broadly, authentication consists of the following steps: 1. Get the credentials from the user 2. Send them to the backend 3. Store the token to make authenticated requests ## How to get credentials from the user[​](#how-to-get-credentials-from-the-user "Direct link to heading") We are assuming that your app is responsible for getting credentials. If you have authentication via OAuth, you can simply create a login page with a link to the OAuth provider's login page and skip to [step 3](#how-to-store-the-token-for-authenticated-requests). ### Dedicated page for login[​](#dedicated-page-for-login "Direct link to heading") Usually, websites have dedicated pages for login, where you enter your username and password. These pages are quite simple, so they don't require decomposition. Login and registration forms are quite similar in appearance, so they can even be grouped into one page. Create a slice for your login/registration page on the Pages layer: * πŸ“‚ pages * πŸ“‚ login * πŸ“‚ ui * πŸ“„ LoginPage.tsx (or your framework's component file format) * πŸ“„ RegisterPage.tsx * πŸ“„ index.ts * other pages… Here we created two components and exported them both in the index file of the slice. These components will contain forms that are responsible for presenting the user with understandable controls to get their credentials. ### Dialog for login[​](#dialog-for-login "Direct link to heading") If your app has a dialog for login that can be used on any page, consider making that dialog a widget. That way, you can still avoid too much decomposition, but have the freedom to reuse this dialog on any page. * πŸ“‚ widgets * πŸ“‚ login-dialog * πŸ“‚ ui * πŸ“„ LoginDialog.tsx * πŸ“„ index.ts * other widgets… The rest of this guide is written for the dedicated page approach, but the same principles apply to the dialog widget. ### Client-side validation[​](#client-side-validation "Direct link to heading") Sometimes, especially for registration, it makes sense to perform client-side validation to let the user know quickly that they made a mistake. Validation can take place in the `model` segment of the login page. Use a schema validation library, for example, [Zod](https://zod.dev) for JS/TS, and expose that schema to the `ui` segment: pages/login/model/registration-schema.ts ``` import { z } from "zod"; export const registrationData = z.object({ email: z.string().email(), password: z.string().min(6), confirmPassword: z.string(), }).refine((data) => data.password === data.confirmPassword, { message: "Passwords do not match", path: ["confirmPassword"], }); ``` Then, in the `ui` segment, you can use this schema to validate the user input: pages/login/ui/RegisterPage.tsx ``` import { registrationData } from "../model/registration-schema"; function validate(formData: FormData) { const data = Object.fromEntries(formData.entries()); try { registrationData.parse(data); } catch (error) { // TODO: Show error message to the user } } export function RegisterPage() { return (
validate(new FormData(e.target))}>
) } ``` ## How to send credentials to the backend[​](#how-to-send-credentials-to-the-backend "Direct link to heading") Create a function that makes a request to your backend's login endpoint. This function can either be called directly in the component code using a mutation library (e.g. TanStack Query), or it can be called as a side effect in a state manager. As explained in the [guide for API requests](/documentation/docs/guides/examples/api-requests.md), you can put your request either in `shared/api` or in the `api` segment of your login page. ### Two-factor authentication[​](#two-factor-authentication "Direct link to heading") If your app supports two-factor authentication (2FA), you might have to redirect to another page where a user can enter a one-time password. Usually your `POST /login` request would return the user object with a flag indicating that the user has 2FA enabled. If that flag is set, redirect the user to the 2FA page. Since this page is very related to logging in, you can also keep it in the same slice, `login` on the Pages layer. You would also need another request function, similar to `login()` that we created above. Place them together, either in Shared, or in the `api` segment of the `login` page. ## How to store the token for authenticated requests[​](#how-to-store-the-token-for-authenticated-requests "Direct link to heading") Regardless of the authentication scheme you have, be it a simple login & password, OAuth, or two-factor authentication, at the end you will receive a token. This token should be stored so that subsequent requests can identify themselves. The ideal token storage for a web app is a **cookie** β€” it requires no manual token storage or handling. As such, cookie storage needs almost no consideration from the frontend architecture side. If your frontend framework has a server side (for example, [Remix](https://remix.run)), then you should store the server-side cookie infrastructure in `shared/api`. There is an example in [the Authentication section of the tutorial](/documentation/docs/get-started/tutorial.md#authentication) of how to do that with Remix. Sometimes, however, cookie storage is not an option. In this case, you will have to store the token manually. Apart from storing the token, you may also need to set up logic for refreshing your token when it expires. With FSD, there are several places where you can store the token, as well as several ways to make it available for the rest of the app. ### In Shared[​](#in-shared "Direct link to heading") This approach plays well with an API client defined in `shared/api` because the token is freely available for other request functions that require authentication to succeed. You can make the API client hold state, either with a reactive store or simply a module-level variable, and update that state in your `login()`/`logout()` functions. Automatic token refresh can be implemented as a middleware in the API client β€” something that can execute every time you make any request. It can work like this: * Authenticate and store the access token as well as the refresh token * Make any request that requires authentication * If the request fails with a status code that indicates token expiration, and there is a token in the store, make a refresh request, store the new tokens, and retry the original request One of the drawbacks of this approach is that the logic of managing and refreshing the token doesn't have a dedicated place. This can be fine for some apps or teams, but if the token management logic is more complex, it may be preferable to separate responsibilities of making requests and managing tokens. You can do that by keeping your requests and API client in `shared/api`, but the token store and management logic in `shared/auth`. Another drawback of this approach is that if your backend returns an object of your current user's information along with the token, you have to store that somewhere or discard that information and request it again from an endpoint like `/me` or `/users/current`. ### In Entities[​](#in-entities "Direct link to heading") It's common for FSD projects to have an entity for a user and/or an entity for the current user. It can even be the same entity for both. note The **current user** is also sometimes called "viewer" or "me". This is to distinguish the single authenticated user, with permissions and private information, from a list of all users with publicly accessible information. To store the token in the User entity, create a reactive store in the `model` segment. That store can contain both the token and the user object. Since the API client is usually defined in `shared/api` or spreaded across the entities, the main challenge to this approach is making the token available to other requests that need it without breaking [the import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers): > A module (file) in a slice can only import other slices when they are located on layers strictly below. There are several solutions to this challenge: 1. **Pass the token manually every time you make a request**
This is the simplest solution, but it quickly becomes cumbersome, and if you don't have type safety, it's easy to forget. It's also not compatible with middlewares pattern for the API client in Shared. 2. **Expose the token to the entire app with a context or a global store like `localStorage`**
The key to retrieve the token will be kept in `shared/api` so that the API client can access it. The reactive store of the token will be exported from the User entity, and the context provider (if needed) will be set up on the App layer. This gives more freedom for designing the API client, however, this creates an implicit dependency on higher layers to provide context. When following this approach, consider providing helpful error messages if the context or `localStorage` are not set up correctly. 3. **Inject the token into the API client every time it changes**
If your store is reactive, you can create a subscription that will update the API client's token store every time the store in the entity changes. This is similar to the previous solution in that they both create an implicit dependency on higher layers, but this one is more imperative ("push"), while the previous one is more declarative ("pull"). Once you overcome the challenge of exposing the token that is stored in the entity's model, you can encode more business logic related to token management. For example, the `model` segment can contain logic to invalidate the token after a certain period of time, or to refresh the token when it expires. To actually make requests to the backend, use the `api` segment of the User entity or `shared/api`. ### In Pages/Widgets (not recommended)[​](#in-pageswidgets-not-recommended "Direct link to heading") It is discouraged to store app-wide state like an access token in pages or widgets. Avoid placing your token store in the `model` segment of the login page, instead choose from the first two solutions, Shared or Entities. ## Logout and token invalidation[​](#logout-and-token-invalidation "Direct link to heading") Usually, apps don't have an entire page for logging out, but the logout functionality is still very important. It consists of an authenticated request to the backend and an update to the token store. If you store all your requests in `shared/api`, keep the logout request function there, close to the login function. Otherwise, consider keeping the logout request function next to the button that triggers it. For example, if you have a header widget that appears on every page and contains the logout link, put that request in the `api` segment of that widget. The update to the token store will have to be triggered from the place of the logout button, like a header widget. You can combine the request and the store update in the `model` segment of that widget. ### Automatic logout[​](#automatic-logout "Direct link to heading") Don't forget to build failsafes for when a request to log out fails, or a request to refresh a login token fails. In both of these cases, you should clear the token store. If you keep your token in Entities, this code can be placed in the `model` segment as it is pure business logic. If you keep your token in Shared, placing this logic in `shared/api` might bloat the segment and dilute its purpose. If you're noticing that your API segment contains two several unrelated things, consider splitting out the token management logic into another segment, for example, `shared/auth`. --- # Autocomplete WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/170) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About decomposition by layers ## See also[​](#see-also "Direct link to heading") * [(Discussion) About the application of the methodology for the selection with loaded dictionaries](https://github.com/feature-sliced/documentation/discussions/65#discussioncomment-480807) --- # Browser API WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/197) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About working with the Browser API: localStorage, audio Api, bluetooth API, etc. > > You can ask about the idea in more detail [@alex\_novi](https://t.me/alex_novich) --- # CMS WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/172) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Features may be different[​](#features-may-be-different "Direct link to heading") In some projects, all the functionality is concentrated in data from the server > ## How to work more correctly with CMS markup[​](#how-to-work-more-correctly-with-cms-markup "Direct link to heading") > > --- # Feedback WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/187) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > Errors, Alerts, Notifications, ... --- # i18n WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/171) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Where to place it? How to work with this?[​](#where-to-place-it-how-to-work-with-this "Direct link to heading") * * * --- # Metric WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/181) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About ways to initialize metrics in the application --- # Monorepositories WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/221) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About applicability for mono repositories, about bff, about microapps ## See also[​](#see-also "Direct link to heading") * [(Discussion) About mono repositories and plug-ins-packages](https://github.com/feature-sliced/documentation/discussions/50) * [(Thread) About the application for a mono repository](https://t.me/feature_sliced/2412) --- # Page layouts This guide examines the abstraction of a *page layout* β€” when several pages share the same overall structure, and differ only in the main content. info Is your question not covered by this guide? Post your question by leaving feedback on this article (blue button on the right) and we will consider expanding this guide! ## Simple layout[​](#simple-layout "Direct link to heading") The simplest layout can be seen on this page. It has a header with site navigation, two sidebars, and a footer with external links. There is no complicated business logic, and the only dynamic parts are sidebars and the switchers on the right side of the header. Such a layout can be placed entirely in `shared/ui` or in `app/layouts`, with props filling in the content for the sidebars: shared/ui/layout/Layout.tsx ``` import { Link, Outlet } from "react-router-dom"; import { useThemeSwitcher } from "./useThemeSwitcher"; export function Layout({ siblingPages, headings }) { const [theme, toggleTheme] = useThemeSwitcher(); return (
{/* This is where the main content goes */}
  • GitHub
  • Twitter
); } ``` shared/ui/layout/useThemeSwitcher.ts ``` export function useThemeSwitcher() { const [theme, setTheme] = useState("light"); function toggleTheme() { setTheme(theme === "light" ? "dark" : "light"); } useEffect(() => { document.body.classList.remove("light", "dark"); document.body.classList.add(theme); }, [theme]); return [theme, toggleTheme] as const; } ``` The code of sidebars is left as an exercise for the reader πŸ˜‰. ## Using widgets in the layout[​](#using-widgets-in-the-layout "Direct link to heading") Sometimes you want to include certain business logic in the layout, especially if you're using deeply nested routes with a router like [React Router](https://reactrouter.com/). Then you can't store the layout in Shared or in Widgets due to [the import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers): > A module in a slice can only import other slices when they are located on layers strictly below. Before we discuss solutions, we need to discuss if it's even a problem in the first place. Do you *really need* that layout, and if so, does it *really need* to be a Widget? If the block of business logic in question is reused on 2-3 pages, and the layout is simply a small wrapper for that widget, consider one of these two options: 1. **Write the layout inline on the App layer, where you configure the routing**
This is great for routers that support nesting, because you can group certain routes and apply the layout only to them. 2. **Just copy-paste it**
The urge to abstract code is often very overrated. It is especially the case for layouts, which rarely change. At some point, if one of these pages will need to change, you can simply do the change without needlessly affecting other pages. If you're worried that someone might forget to update the other pages, you can always leave a comment that describes the relationship between the pages. If none of the above are applicable, there are two solutions to include a widget in the layout: 1. **Use render props or slots**
Most frameworks allow you to pass a piece of UI externally. In React, it's called [render props](https://www.patterns.dev/react/render-props-pattern/), in Vue it's called [slots](https://vuejs.org/guide/components/slots). 2. **Move the layout to the App layer**
You can also store your layout on the App layer, for example, in `app/layouts`, and compose any widgets you want. ## Further reading[​](#further-reading "Direct link to heading") * There's an example of how to build a layout with authentication with React and Remix (equivalent to React Router) in the [tutorial](/documentation/docs/get-started/tutorial.md). --- # Desktop/Touch platforms WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/198) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the application of the methodology for desktop/touch --- # SSR WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/173) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > About the implementation of SSR using the methodology --- # Theme WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/207) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Where should I put my work with the theme and palette?[​](#where-should-i-put-my-work-with-the-theme-and-palette "Direct link to heading") > ## Discussion about the location of the theme, i18n logic[​](#discussion-about-the-location-of-the-theme-i18n-logic "Direct link to heading") > --- # Types This guide concerns data types from typed languages like TypeScript and describes where they fit within FSD. info Is your question not covered by this guide? Post your question by leaving feedback on this article (blue button on the right) and we will consider expanding this guide! ## Utility types[​](#utility-types "Direct link to heading") Utility types are types that don't have much meaning on their own and are usually used with other types. For example: ``` type ArrayValues = T[number]; ``` Source: To make utility types available across your project, either install a library like [`type-fest`](https://github.com/sindresorhus/type-fest), or create your own library in `shared/lib`. Make sure to clearly indicate what new types *should* be added to this library, and what types *don't belong* there. For example, call it `shared/lib/utility-types` and add a README inside that describes what is a utility type in your team. Don't overestimate the potential reusability of a utility type. Just because it can be reused, doesn't mean it will be, and as such, not every utility type needs to be in Shared. Some utility types are fine right next to where they are needed: * πŸ“‚ pages * πŸ“‚ home * πŸ“‚ api * πŸ“„ ArrayValues.ts (utility type) * πŸ“„ getMemoryUsageMetrics.ts (the code that uses the utility type) warning Resist the temptation to create a `shared/types` folder, or to add a `types` segment to your slices. The category "types" is similar to the category "components" or "hooks" in that it describes what the contents are, not what they are for. Segments should describe the purpose of the code, not the essence. ## Business entities and their cross-references[​](#business-entities-and-their-cross-references "Direct link to heading") Among the most important types in an app are the types of business entities, i.e. the real-world things that your app works with. For example, in a music streaming app, you might have business entities *Song*, *Album*, etc. Business entities often come from the backend, so the first step is to type the backend responses. It's convenient to have a function to make a request to every endpoint, and to type the response of this function. For extra type safety, you may want to run the response through a schema validation library like [Zod](https://zod.dev). For example, if you keep all your requests in Shared, you could do it like this: shared/api/songs.ts ``` import type { Artist } from "./artists"; interface Song { id: number; title: string; artists: Array; } export function listSongs() { return fetch('/api/songs').then((res) => res.json() as Promise>); } ``` You might notice that the `Song` type references a different entity, `Artist`. This is a benefit of storing your requests in Shared β€” real-world types are often intertwined. If we kept this function in `entities/song/api`, we wouldn't be able to simply import `Artist` from `entities/artist`, because FSD restricts cross-imports between slices with [the import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers): > A module in a slice can only import other slices when they are located on layers strictly below. There are two ways to deal with this issue: 1. **Parametrize your types**
You can make your types accept type arguments as slots for connections with other entities, and even impose constraints on those slots. For example: entities/song/model/song.ts ``` interface Song { id: number; title: string; artists: Array; } ``` This works better for some types than others. A simple type like `Cart = { items: Array }` can easily be made to work with any type of product. More connected types, like `Country` and `City`, may not be as easy to separate. 2. **Cross-import (but do it right)**
To make cross-imports between entities in FSD, you can use a special public API specifically for each slice that will be cross-importing. For example, if we have entities `song`, `artist`, and `playlist`, and the latter two need to reference `song`, we can make two special public APIs for both of them in the `song` entity with the `@x` notation: * πŸ“‚ entities * πŸ“‚ song * πŸ“‚ @x * πŸ“„ artist.ts (a public API for the `artist` entity to import from) * πŸ“„ playlist.ts (a public API for the `playlist` entity to import from) * πŸ“„ index.ts (regular public API) The contents of a file `πŸ“„ entities/song/@x/artist.ts` are similar to `πŸ“„ entities/song/index.ts`: entities/song/@x/artist.ts ``` export type { Song } from "../model/song.ts"; ``` Then the `πŸ“„ entities/artist/model/artist.ts` can import `Song` like this: entities/artist/model/artist.ts ``` import type { Song } from "entities/song/@x/artist"; export interface Artist { name: string; songs: Array; } ``` By making explicit connections between entities, we stay on top of inter-dependencies and maintain a decent level of domain separation. ## Data transfer objects and mappers[​](#data-transfer-objects-and-mappers "Direct link to heading") Data transfer objects, or DTOs, is a term that describes the shape of data that comes from the backend. Sometimes, the DTO is fine to use as is, but sometimes it's inconvenient for the frontend. That's where mappers come in β€” they transform a DTO into a more convenient shape. ### Where to put DTOs[​](#where-to-put-dtos "Direct link to heading") If you have backend types in a separate package (for example, if you share code between the frontend and the backend), then just import your DTOs from there and you're done! If you don't share code between the backend and frontend, then you need to keep DTOs somewhere in your frontend codebase, and we will explore this case below. If you have your request functions in `shared/api`, that's where the DTOs should be, right next to the function that uses them: shared/api/songs.ts ``` import type { ArtistDTO } from "./artists"; interface SongDTO { id: number; title: string; artist_ids: Array; } export function listSongs() { return fetch('/api/songs').then((res) => res.json() as Promise>); } ``` As mentioned in the previous section, storing your requests and DTOs in Shared comes with the benefit of being able to reference other DTOs. ### Where to put mappers[​](#where-to-put-mappers "Direct link to heading") Mappers are functions that accept a DTO for transformation, and as such, they should be located near the definition of the DTO. In practice this means that if your requests and DTOs are defined in `shared/api`, then the mappers should go there as well: shared/api/songs.ts ``` import type { ArtistDTO } from "./artists"; interface SongDTO { id: number; title: string; disc_no: number; artist_ids: Array; } interface Song { id: string; title: string; /** The full title of the song, including the disc number. */ fullTitle: string; artistIds: Array; } function adaptSongDTO(dto: SongDTO): Song { return { id: String(dto.id), title: dto.title, fullTitle: `${dto.disc_no} / ${dto.title}`, artistIds: dto.artist_ids.map(String), }; } export function listSongs() { return fetch('/api/songs').then(async (res) => (await res.json()).map(adaptSongDTO)); } ``` If your requests and stores are defined in entity slices, then all this code would go there, keeping in mind the limitations of cross-imports between slices: entities/song/api/dto.ts ``` import type { ArtistDTO } from "entities/artist/@x/song"; export interface SongDTO { id: number; title: string; disc_no: number; artist_ids: Array; } ``` entities/song/api/mapper.ts ``` import type { SongDTO } from "./dto"; export interface Song { id: string; title: string; /** The full title of the song, including the disc number. */ fullTitle: string; artistIds: Array; } export function adaptSongDTO(dto: SongDTO): Song { return { id: String(dto.id), title: dto.title, fullTitle: `${dto.disc_no} / ${dto.title}`, artistIds: dto.artist_ids.map(String), }; } ``` entities/song/api/listSongs.ts ``` import { adaptSongDTO } from "./mapper"; export function listSongs() { return fetch('/api/songs').then(async (res) => (await res.json()).map(adaptSongDTO)); } ``` entities/song/model/songs.ts ``` import { createSlice, createEntityAdapter } from "@reduxjs/toolkit"; import { listSongs } from "../api/listSongs"; export const fetchSongs = createAsyncThunk('songs/fetchSongs', listSongs); const songAdapter = createEntityAdapter(); const songsSlice = createSlice({ name: "songs", initialState: songAdapter.getInitialState(), reducers: {}, extraReducers: (builder) => { builder.addCase(fetchSongs.fulfilled, (state, action) => { songAdapter.upsertMany(state, action.payload); }) }, }); ``` ### How to deal with nested DTOs[​](#how-to-deal-with-nested-dtos "Direct link to heading") The most problematic part is when a response from the backend contains several entities. For example, if the song included not just the authors' IDs, but the entire author objects. In this case, it is impossible for entities not to know about each other (unless we want to discard the data or have a firm conversation with the backend team). Instead of coming up with solutions for indirect connections between slices (such as a common middleware that would dispatch actions to other slices), prefer explicit cross-imports with the `@x` notation. Here is how we can implement it with Redux Toolkit: entities/song/model/songs.ts ``` import { createSlice, createEntityAdapter, createAsyncThunk, createSelector, } from '@reduxjs/toolkit' import { normalize, schema } from 'normalizr' import { getSong } from "../api/getSong"; // Define normalizr entity schemas export const artistEntity = new schema.Entity('artists') export const songEntity = new schema.Entity('songs', { artists: [artistEntity], }) const songAdapter = createEntityAdapter() export const fetchSong = createAsyncThunk( 'songs/fetchSong', async (id: string) => { const data = await getSong(id) // Normalize the data so reducers can load a predictable payload, like: // `action.payload = { songs: {}, artists: {} }` const normalized = normalize(data, songEntity) return normalized.entities } ) export const slice = createSlice({ name: 'songs', initialState: songAdapter.getInitialState(), reducers: {}, extraReducers: (builder) => { builder.addCase(fetchSong.fulfilled, (state, action) => { songAdapter.upsertMany(state, action.payload.songs) }) }, }) const reducer = slice.reducer export default reducer ``` entities/song/@x/artist.ts ``` export { fetchSong } from "../model/songs"; ``` entities/artist/model/artists.ts ``` import { createSlice, createEntityAdapter } from '@reduxjs/toolkit' import { fetchSong } from 'entities/song/@x/artist' const artistAdapter = createEntityAdapter() export const slice = createSlice({ name: 'users', initialState: artistAdapter.getInitialState(), reducers: {}, extraReducers: (builder) => { builder.addCase(fetchSong.fulfilled, (state, action) => { // And handle the same fetch result by inserting the artists here artistAdapter.upsertMany(state, action.payload.artists) }) }, }) const reducer = slice.reducer export default reducer ``` This slightly limits the benefits of slice isolation, but it accurately represents a connection between these two entities that we have no control over. If these entities are to ever be refactored, they have to be refactored together. ## Global types and Redux[​](#global-types-and-redux "Direct link to heading") Global types are types that will be used across the whole application. There are two kinds of global types, based on what they need to know about: 1. Generic types that don't have any application specifics 2. Types that need to know about the whole application The first case is simple to resolve β€” place your types in Shared, in an appropriate segment. For example, if you have an interface for a global variable for analytics, you can put it in `shared/analytics`. warning Avoid creating the `shared/types` folder. It groups unrelated things based only on the property of "being a type", and that property is usually not useful when searching for code in a project. The second case is commonly encountered in projects with Redux without RTK. Your final store type is only available once you add all the reducers together, but this store type needs to be available to selectors that you use across the app. For example, here's your typical store definition: app/store/index.ts ``` import { combineReducers, rootReducer } from "redux"; import { songReducer } from "entities/song"; import { artistReducer } from "entities/artist"; const rootReducer = combineReducers(songReducer, artistReducer); const store = createStore(rootReducer); type RootState = ReturnType; type AppDispatch = typeof store.dispatch; ``` It would be nice to have typed Redux hooks `useAppDispatch` and `useAppSelector` in `shared/store`, but they cannot import `RootState` and `AppDispatch` from the App layer due to the [import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers): > A module in a slice can only import other slices when they are located on layers strictly below. The recommended solution in this case is to create an implicit dependency between layers Shared and App. These two types, `RootState` and `AppDispatch` are unlikely to change, and they will be familiar to Redux developers, so we don't have to worry about them as much. In TypeScript, you can do it by declaring the types as global like this: app/store/index.ts ``` /* same content as in the code block before… */ declare type RootState = ReturnType; declare type AppDispatch = typeof store.dispatch; ``` shared/store/index.ts ``` import { useDispatch, useSelector, type TypedUseSelectorHook } from "react-redux"; export const useAppDispatch = useDispatch.withTypes() export const useAppSelector: TypedUseSelectorHook = useSelector; ``` ## Enums[​](#enums "Direct link to heading") The general rule with enums is that they should be defined **as close to the usage locations as possible**. When an enum represents values specific to a single feature, it should be defined in that same feature. The choice of segment should be dictated by usage locations as well. If your enum contains, for example, positions of a toast on the screen, it should be placed in the `ui` segment. If it represents the loading state of a backend operation, it should be placed in the `api` segment. Some enums are truly common across the whole project, like general backend response statuses or design system tokens. In this case, you can place them in Shared, and choose the segment based on what the enum represents (`api` for response statuses, `ui` for design tokens, etc.). ## Type validation schemas and Zod[​](#type-validation-schemas-and-zod "Direct link to heading") If you want to validate that your data conforms to a certain shape or constraints, you can define a validation schema. In TypeScript, a popular library for this job is [Zod](https://zod.dev). Validation schemas should also be colocated with the code that uses them, as much as possible. Validation schemas are similar to mappers (as discussed in the [Data transfer objects and mappers](#data-transfer-objects-and-mappers) section) in the sense that they take a data transfer object and parse it, producing an error if the parsing fails. One of the most common cases of validation is for the data that comes from the backend. Typically, you want to fail the request when the data doesn't match the schema, so it makes sense to put the schema in the same place as the request function, which is usually the `api` segment. If your data comes through user input, like a form, the validation should happen as the data is being entered. You can place your schema in the `ui` segment, next to the form component, or in the `model` segment, if the `ui` segment is too crowded. ## Typings of component props and context[​](#typings-of-component-props-and-context "Direct link to heading") In general, it's best to keep the props or context interface in the same file as the component or context that uses them. If you have a framework with single-file components, like Vue or Svelte, and you can't define the props interface in the same file, or you want to share that interface between several components, create a separate file in the same folder, typically, the `ui` segment. Here's an example with JSX (React or Solid): pages/home/ui/RecentActions.tsx ``` interface RecentActionsProps { actions: Array<{ id: string; text: string }>; } export function RecentActions({ actions }: RecentActionsProps) { /* … */ } ``` And here's an example with the interface stored in a separate file for Vue: pages/home/ui/RecentActionsProps.ts ``` export interface RecentActionsProps { actions: Array<{ id: string; text: string }>; } ``` pages/home/ui/RecentActions.vue ``` ``` ## Ambient declaration files (`*.d.ts`)[​](#ambient-declaration-files-dts "Direct link to heading") Some packages, for example, [Vite](https://vitejs.dev) or [ts-reset](https://www.totaltypescript.com/ts-reset), require ambient declaration files to work across your app. Usually, they aren't large or complicated, so they often don't require any architecting, it's fine to just throw them in the `src/` folder. To keep the `src` more organized, you can keep them on the App layer, in `app/ambient/`. Other packages simply don't have typings, and you might want to declare them as untyped or even write your own typings for them. A good place for those typings would be `shared/lib`, in a folder like `shared/lib/untyped-packages`. Create a `%LIBRARY_NAME%.d.ts` file there and declare the types you need: shared/lib/untyped-packages/use-react-screenshot.d.ts ``` // This library doesn't have typings, and we didn't want to bother writing our own. declare module "use-react-screenshot"; ``` ## Auto-generation of types[​](#auto-generation-of-types "Direct link to heading") It's common to generate types from external sources, for example, generating backend types from an OpenAPI schema. In this case, create a dedicated place in your codebase for these types, like `shared/api/openapi`. Ideally, you should also include a README in that folder that describes what these files are, how to regenerate them, etc. --- # White Labels WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/215) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > Figma, brand uikit, templates, adaptability to brands ## See also[​](#see-also "Direct link to heading") * [(Thread) About the application for white-labels (branded) projects](https://t.me/feature_sliced/1543) * [(Presentation) About white-labels apps and design](http://yadi.sk/i/5IdhzsWrpO3v4Q) --- # Cross-imports WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/220) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* > Cross-imports appear when the layer or abstraction begins to take too much responsibility than it should. That is why the methodology identifies new layers that allow you to uncouple these cross-imports ## See also[​](#see-also "Direct link to heading") * [(Thread) About the supposed inevitability of cross-ports](https://t.me/feature_sliced/4515) * [(Thread) About resolving cross-ports in entities](https://t.me/feature_sliced/3678) * [(Thread) About cross-imports and responsibility](https://t.me/feature_sliced/3287) * [(Thread) About imports between segments](https://t.me/feature_sliced/4021) * [(Thread) About cross-imports inside shared](https://t.me/feature_sliced/3618) --- # Desegemented WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/148) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Situation[​](#situation "Direct link to heading") Very often, there is a situation on projects when modules related to a specific domain from the subject area are unnecessarily desegmented and scattered around the project ``` β”œβ”€β”€ components/ | β”œβ”€β”€ DeliveryCard | β”œβ”€β”€ DeliveryChoice | β”œβ”€β”€ RegionSelect | β”œβ”€β”€ UserAvatar β”œβ”€β”€ actions/ | β”œβ”€β”€ delivery.js | β”œβ”€β”€ region.js | β”œβ”€β”€ user.js β”œβ”€β”€ epics/ | β”œβ”€β”€ delivery.js | β”œβ”€β”€ region.js | β”œβ”€β”€ user.js β”œβ”€β”€ constants/ | β”œβ”€β”€ delivery.js | β”œβ”€β”€ region.js | β”œβ”€β”€ user.js β”œβ”€β”€ helpers/ | β”œβ”€β”€ delivery.js | β”œβ”€β”€ region.js | β”œβ”€β”€ user.js β”œβ”€β”€ entities/ | β”œβ”€β”€ delivery/ | | β”œβ”€β”€ getters.js | | β”œβ”€β”€ selectors.js | β”œβ”€β”€ region/ | β”œβ”€β”€ user/ ``` ## Problem[​](#problem "Direct link to heading") The problem manifests itself at least in violation of the principle of \* \* High Cohesion\*\* and excessive stretching \* \* of the axis of changes\*\* ## If you ignore it[​](#if-you-ignore-it "Direct link to heading") * If necessary, touch on the logic, for example, delivery - we will have to keep in mind that it lies in several places and touch on several places in the code-which unnecessarily stretches our \* \* Axis of changes\*\* * If we need to study the logic of the user, we will have to go through the whole project to study in detail \* \* actions, epics, constants, entities, components\*\* - instead of it lying in one place * Implicit connections and the uncontrollability of a growing subject area * With this approach, the eye is very often blurred and you may not notice how we "create constants for the sake of constants", creating a dump in the corresponding project directory ## Solution[​](#solution "Direct link to heading") Place all modules related to a specific domain/user case - directly next to each other So that when studying a particular module, all its components lie side by side, and are not scattered around the project > It also increases the discoverability and clarity of the code base and the relationships between modules ``` - β”œβ”€β”€ components/ - | β”œβ”€β”€ DeliveryCard - | β”œβ”€β”€ DeliveryChoice - | β”œβ”€β”€ RegionSelect - | β”œβ”€β”€ UserAvatar - β”œβ”€β”€ actions/ - | β”œβ”€β”€ delivery.js - | β”œβ”€β”€ region.js - | β”œβ”€β”€ user.js - β”œβ”€β”€ epics/{...} - β”œβ”€β”€ constants/{...} - β”œβ”€β”€ helpers/{...} β”œβ”€β”€ entities/ | β”œβ”€β”€ delivery/ + | | β”œβ”€β”€ ui/ # ~ components/ + | | | β”œβ”€β”€ card.js + | | | β”œβ”€β”€ choice.js + | | β”œβ”€β”€ model/ + | | | β”œβ”€β”€ actions.js + | | | β”œβ”€β”€ constants.js + | | | β”œβ”€β”€ epics.js + | | | β”œβ”€β”€ getters.js + | | | β”œβ”€β”€ selectors.js + | | β”œβ”€β”€ lib/ # ~ helpers | β”œβ”€β”€ region/ | β”œβ”€β”€ user/ ``` ## See also[​](#see-also "Direct link to heading") * [(Article) About Low Coupling and High Cohesion clearly](https://enterprisecraftsmanship.com/posts/cohesion-coupling-difference/) * [(Article) Low Coupling and High Cohesion. The Law of Demeter](https://medium.com/german-gorelkin/low-coupling-high-cohesion-d36369fb1be9) --- # Routing WIP The article is in the process of writing To bring the release of the article closer, you can: * πŸ“’ Share your feedback [at article (comment/emoji-reaction)](https://github.com/feature-sliced/documentation/issues/169) * πŸ’¬ Collect the relevant [material on the topic from chat](https://t.me/feature_sliced) * βš’οΈ Contribute [in any other way](https://github.com/feature-sliced/documentation/blob/master/CONTRIBUTING.md)
*🍰 Stay tuned!* ## Situation[​](#situation "Direct link to heading") Urls to pages are hardcoded in the layers below pages entities/post/card ``` ... ``` ## Problem[​](#problem "Direct link to heading") Urls are not concentrated in the page layer, where they belong according to the scope of responsibility ## If you ignore it[​](#if-you-ignore-it "Direct link to heading") Then, when changing urls, you will have to keep in mind that these urls (and the logic of urls/redirects) can be in all layers except pages And it also means that now even a simple product card takes part of the responsibility from the pages, which smears the logic of the project ## Solution[​](#solution "Direct link to heading") Determine how to work with urls/redirects from the page level and above Transfer to the layers below via composition/props/factories ## See also[​](#see-also "Direct link to heading") * [(Thread) What if I "sew up" routing in entities/features/widgets](https://t.me/feature_sliced/4389) * [(Thread) Why does it smear the logic of routes only in pages](https://t.me/feature_sliced/3756) --- # Migration from a custom architecture This guide describes an approach that might be helpful when migrating from a custom self-made architecture to Feature-Sliced Design. Here is the folder structure of a typical custom architecture. We will be using it as an example in this guide.
Click on the blue arrow to open the folder. πŸ“ src * πŸ“ actions * πŸ“ product * πŸ“ order * πŸ“ api * πŸ“ components * πŸ“ containers * πŸ“ constants * πŸ“ i18n * πŸ“ modules * πŸ“ helpers * πŸ“ routes * πŸ“ products.jsx * πŸ“„ products.\[id].jsx * πŸ“ utils * πŸ“ reducers * πŸ“ selectors * πŸ“ styles * πŸ“„ App.jsx * πŸ“„ index.js ## Before you start[​](#before-you-start "Direct link to heading") The most important question to ask your team when considering to switch to Feature-Sliced Design is β€” *do you really need it?* We love Feature-Sliced Design, but even we recognize that some projects are perfectly fine without it. Here are some reasons to consider making the switch: 1. New team members are complaining that it's hard to get to a productive level 2. Making modifications to one part of the code **often** causes another unrelated part to break 3. Adding new functionality is difficult due to the sheer amount of things you need to think about **Avoid switching to FSD against the will of your teammates**, even if you are the lead.
First, convince your teammates that the benefits outweigh the cost of migration and the cost of learning a new architecture instead of the established one. Also keep in mind that any kind of architectural changes are not immediately observable to the management. Make sure they are on board with the switch before starting and explain to them why it might benefit the project. tip If you need help convincing the project manager that FSD is beneficial, consider some of these points: 1. Migration to FSD can happen incrementally, so it will not halt the development of new features 2. A good architecture can significantly decrease the time that a new developer needs to get productive 3. FSD is a documented architecture, so the team doesn't have to continuously spend time on maintaining their own documentation *** If you made the decision to start migrating, then the first thing you want to do is to set up an alias for `πŸ“ src`. It will be helpful later to refer to top-level folders. We will consider `@` as an alias for `./src` for the rest of this guide. ## Step 1. Divide the code by pages[​](#divide-code-by-pages "Direct link to heading") Most custom architectures already have a division by pages, however small or large in logic. If you already have `πŸ“ pages`, you may skip this step. If you only have `πŸ“ routes`, create `πŸ“ pages` and try to move as much component code from `πŸ“ routes` as possible. Ideally, you would have a tiny route and a larger page. As you're moving code, create a folder for each page and add an index file: note For now, it's okay if your pages reference each other. You can tackle that later, but for now, focus on establishing a prominent division by pages. Route file: src/routes/products.\[id].js ``` export { ProductPage as default } from "@/pages/product" ``` Page index file: src/pages/product/index.js ``` export { ProductPage } from "./ProductPage.jsx" ``` Page component file: src/pages/product/ProductPage.jsx ``` export function ProductPage(props) { return
; } ``` ## Step 2. Separate everything else from the pages[​](#separate-everything-else-from-pages "Direct link to heading") Create a folder `πŸ“ src/shared` and move everything that doesn't import from `πŸ“ pages` or `πŸ“ routes` there. Create a folder `πŸ“ src/app` and move everything that does import the pages or routes there, including the routes themselves. Remember that the Shared layer doesn't have slices, so it's fine if segments import from each other. You should end up with a file structure like this: πŸ“ src * πŸ“ app * πŸ“ routes * πŸ“„ products.jsx * πŸ“„ products.\[id].jsx * πŸ“„ App.jsx * πŸ“„ index.js * πŸ“ pages * πŸ“ product * πŸ“ ui * πŸ“„ ProductPage.jsx * πŸ“„ index.js * πŸ“ catalog * πŸ“ shared * πŸ“ actions * πŸ“ api * πŸ“ components * πŸ“ containers * πŸ“ constants * πŸ“ i18n * πŸ“ modules * πŸ“ helpers * πŸ“ utils * πŸ“ reducers * πŸ“ selectors * πŸ“ styles ## Step 3. Tackle cross-imports between pages[​](#tackle-cross-imports-between-pages "Direct link to heading") Find all instances where one page is importing from the other and do one of the two things: 1. Copy-paste the imported code into the depending page to remove the dependency 2. Move the code to a proper segment in Shared: * if it's a part of the UI kit, move it to `πŸ“ shared/ui`; * if it's a configuration constant, move it to `πŸ“ shared/config`; * if it's a backend interaction, move it to `πŸ“ shared/api`. note **Copy-pasting isn't architecturally wrong**, in fact, sometimes it may be more correct to duplicate than to abstract into a new reusable module. The reason is that sometimes the shared parts of pages start drifting apart, and you don't want dependencies getting in your way in these cases. However, there is still sense in the DRY ("don't repeat yourself") principle, so make sure you're not copy-pasting business logic. Otherwise you will need to remember to fix bugs in several places at once. ## Step 4. Unpack the Shared layer[​](#unpack-shared-layer "Direct link to heading") You might have a lot of stuff in the Shared layer on this step, and you generally want to avoid that. The reason is that the Shared layer may be a dependency for any other layer in your codebase, so making changes to that code is automatically more prone to unintended consequences. Find all the objects that are only used on one page and move it to the slice of that page. And yes, *that applies to actions, reducers, and selectors, too*. There is no benefit in grouping all actions together, but there is benefit in colocating relevant actions close to their usage. You should end up with a file structure like this: πŸ“ src * πŸ“ app (unchanged) * πŸ“ pages * πŸ“ product * πŸ“ actions * πŸ“ reducers * πŸ“ selectors * πŸ“ ui * πŸ“„ Component.jsx * πŸ“„ Container.jsx * πŸ“„ ProductPage.jsx * πŸ“„ index.js * πŸ“ catalog * πŸ“ shared (only objects that are reused) * πŸ“ actions * πŸ“ api * πŸ“ components * πŸ“ containers * πŸ“ constants * πŸ“ i18n * πŸ“ modules * πŸ“ helpers * πŸ“ utils * πŸ“ reducers * πŸ“ selectors * πŸ“ styles ## Step 5. Organize code by technical purpose[​](#organize-by-technical-purpose "Direct link to heading") In FSD, division by technical purpose is done with *segments*. There are a few common ones: * `ui` β€” everything related to UI display: UI components, date formatters, styles, etc. * `api` β€” backend interactions: request functions, data types, mappers, etc. * `model` β€” the data model: schemas, interfaces, stores, and business logic. * `lib` β€” library code that other modules on this slice need. * `config` β€” configuration files and feature flags. You can create your own segments, too, if you need. Make sure not to create segments that group code by what it is, like `components`, `actions`, `types`, `utils`. Instead, group the code by what it's for. Reorganize your pages to separate code by segments. You should already have a `ui` segment, now it's time to create other segments, like `model` for your actions, reducers, and selectors, or `api` for your thunks and mutations. Also reorganize the Shared layer to remove these folders: * `πŸ“ components`, `πŸ“ containers` β€” most of it should become `πŸ“ shared/ui`; * `πŸ“ helpers`, `πŸ“ utils` β€” if there are some reused helpers left, group them together by function, like dates or type conversions, and move theses groups to `πŸ“ shared/lib`; * `πŸ“ constants` β€” again, group by function and move to `πŸ“ shared/config`. ## Optional steps[​](#optional-steps "Direct link to heading") ### Step 6. Form entities/features from Redux slices that are used on several pages[​](#form-entities-features-from-redux "Direct link to heading") Usually, these reused Redux slices will describe something relevant to the business, for example, products or users, so these can be moved to the Entities layer, one entity per one folder. If the Redux slice is related to an action that your users want to do in your app, like comments, then you can move it to the Features layer. Entities and features are meant to be independent from each other. If your business domain contains inherent connections between entities, refer to the [guide on business entities](/documentation/docs/guides/examples/types.md#business-entities-and-their-cross-references) for advice on how to organize these connections. The API functions related to these slices can stay in `πŸ“ shared/api`. ### Step 7. Refactor your modules[​](#refactor-your-modules "Direct link to heading") The `πŸ“ modules` folder is commonly used for business logic, so it's already pretty similar in nature to the Features layer from FSD. Some modules might also be describe large chunks of the UI, like an app header. In that case, you should migrate them to the Widgets layer. ### Step 8. Form a clean UI foundation in `shared/ui`[​](#form-clean-ui-foundation "Direct link to heading") `πŸ“ shared/ui` should ideally contain a set of UI elements that don't have any business logic encoded in them. They should also be highly reusable. Refactor the UI components that used to be in `πŸ“ components` and `πŸ“ containers` to separate out the business logic. Move that business logic to the higher layers. If it's not used in too many places, you could even consider copy-pasting. ## See also[​](#see-also "Direct link to heading") * [(Talk in Russian) Ilya Klimov β€” ΠšΡ€Ρ‹ΡΠΈΠ½Ρ‹Π΅ Π±Π΅Π³Π° бСсконСчного Ρ€Π΅Ρ„Π°ΠΊΡ‚ΠΎΡ€ΠΈΠ½Π³Π°: ΠΊΠ°ΠΊ Π½Π΅ Π΄Π°Ρ‚ΡŒ тСхничСскому Π΄ΠΎΠ»Π³Ρƒ ΡƒΠ±ΠΈΡ‚ΡŒ ΠΌΠΎΡ‚ΠΈΠ²Π°Ρ†ΠΈΡŽ ΠΈ ΠΏΡ€ΠΎΠ΄ΡƒΠΊΡ‚](https://youtu.be/aOiJ3k2UvO4) --- # Migration from v1 to v2 ## Why v2?[​](#why-v2 "Direct link to heading") The original concept of **feature-slices** [was announced](https://t.me/feature_slices) in 2018. Since then, many transformations of the methodology have taken place, but at the same time **[the basic principles were preserved](https://feature-sliced.github.io/featureslices.dev/v1.0.html)**: * Using a *standardized* frontend project structure * Splitting the application in the first place-according to *business logic* * Use of *isolated features* to prevent implicit side effects and cyclic dependencies * Using the *Public API* with a ban on climbing "into the insides" of the module At the same time, in the previous version of the methodology, there were still **weak points** that * Sometimes it leads to boilerplate code * Sometimes it leads to excessive complication of the code base and non-obvious rules between abstractions * Sometimes it leads to implicit architectural solutions, which prevented the project from being pulled up and new people from onboarding The new version of the methodology ([v2](https://github.com/feature-sliced/documentation)) is designed **to eliminate these shortcomings, while preserving the existing advantages** of the approach. Since 2018, [has also developed](https://github.com/kof/feature-driven-architecture/issues) another similar methodology - [**feature-driven**](https://github.com/feature-sliced/documentation/tree/rc/feature-driven), which was first announced by [Oleg Isonen](https://github.com/kof). After merging of the two approaches, we have **improved and refined existing practices** - towards greater flexibility, clarity and efficiency in application. > As a result, this has even affected the name of the methodology - *"feature-slice**d**"* ## Why does it make sense to migrate the project to v2?[​](#why-does-it-make-sense-to-migrate-the-project-to-v2 "Direct link to heading") > `WIP:` The current version of the methodology is under development and some details *may change* #### πŸ” More transparent and simple architecture[​](#-more-transparent-and-simple-architecture "Direct link to heading") The methodology (v2) offers **more intuitive and more common abstractions and ways of separating logic among developers.** All this has an extremely positive effect on attracting new people, as well as studying the current state of the project, and distributing the business logic of the application. #### πŸ“¦ More flexible and honest modularity[​](#-more-flexible-and-honest-modularity "Direct link to heading") The methodology (v2) allows **to distribute logic in a more flexible way:** * With the ability to refactor isolated parts from scratch * With the ability to rely on the same abstractions, but without unnecessary interweaving of dependencies * With simpler requirements for the location of the new module *(layer => slice => segment)* #### πŸš€ More specifications, plans, community[​](#-more-specifications-plans-community "Direct link to heading") At the moment, the `core-team` is actively working on the latest (v2) version of the methodology So it is for her: * there will be more described cases / problems * there will be more guides on the application * there will be more real examples * in general, there will be more documentation for onboarding new people and studying the concepts of the methodology * the toolkit will be developed in the future to comply with the concepts and conventions on architecture > Of course, there will be user support for the first version as well - but the latest version is still a priority for us > > In the future, with the next major updates, you will still have access to the current version (v2) of the methodology, **without risks for your teams and projects** ## Changelog[​](#changelog "Direct link to heading") ### `BREAKING` Layers[​](#breaking-layers "Direct link to heading") Now the methodology assumes explicit allocation of layers at the top level * `/app` > `/processes` > **`/pages`** > **`/features`** > `/entities` > `/shared` * *That is, not everything is now treated as features/pages* * This approach allows you to [explicitly set rules for layers](https://t.me/atomicdesign/18708): * The **higher the layer** of the module is located , the more **context** it has *(in other words-each module of the layer - can import only the modules of the underlying layers, but not higher)* * The **lower the layer of the** module is located , the more **danger and responsibility** to make changes to it *(because it is usually the underlying layers that are more overused)* ### `BREAKING` Shared[​](#breaking-shared "Direct link to heading") The infrastructure abstractions `/ui`, `/lib`, `/api`, which used to lie in the src root of the project, are now separated by a separate directory `/src/shared` * `shared/ui` - Still the same general uikit of the application (optional) * *At the same time, no one forbids using `Atomic Design` here as before* * `shared/lib` - A set of auxiliary libraries for implementing logic * *Still - without a dump of helpers* * `shared/api` - A common entry point for accessing the API * *Can also be registered locally in each feature / page - but it is not recommended* * As before - there should be no explicit binding to business logic in `shared` * *If necessary, you need to take this relationship to the `entities` level or even higher* ### `NEW` Entities, Processes[​](#new-entities-processes "Direct link to heading") In v2 **, other new abstractions** have been added to eliminate the problems of logic complexity and high coupling. * `/entities` - layer **business entities** containing slices that are related directly to the business models or synthetic entities required only on frontend * *Examples: `user`, `i18n`, `order`, `blog`* * `/processes` - layer **business processes**, penetrating app * **The layer is optional**, it is usually recommended to use it when *the logic grows and begins to blur in several pages* * *Examples: `payment`, `auth`, `quick-tour`* ### `BREAKING` Abstractions & Naming[​](#breaking-abstractions--naming "Direct link to heading") Now specific abstractions and [clear recommendations for naming them](/documentation/docs/about/understanding/naming.md)are defined #### Layers[​](#layers "Direct link to heading") * `/app` β€” **application initialization layer** * *Previous versions: `app`, `core`,`init`, `src/index` (and this happens)* * `/processes` β€” [**business process layer**](https://github.com/feature-sliced/documentation/discussions/20) * *Previous versions: `processes`, `flows`, `workflows`* * `/pages` β€” **application page layer** * *Previous versions: `pages`, `screens`, `views`, `layouts`, `components`, `containers`* * `/features` β€” [**functionality parts layer**](https://github.com/feature-sliced/documentation/discussions/23) * *Previous versions: `features`, `components`, `containers`* * `/entities` β€” [**business entity layer**](https://github.com/feature-sliced/documentation/discussions/18#discussioncomment-422649) * *Previous versions: `entities`, `models`, `shared`* * `/shared` β€” [**layer of reused infrastructure code**](https://github.com/feature-sliced/documentation/discussions/31#discussioncomment-453020) πŸ”₯ * *Previous versions: `shared`, `common`, `lib`* #### Segments[​](#segments "Direct link to heading") * `/ui` β€” [**UI segment**](https://github.com/feature-sliced/documentation/discussions/31#discussioncomment-453132) πŸ”₯ * *Previous versions: `ui`, `components`, `view`* * `/model` β€” [**BL-segment**](https://github.com/feature-sliced/documentation/discussions/31#discussioncomment-472645) πŸ”₯ * *Previous versions: `model`, `store`, `state`, `services`, `controller`* * `/lib` β€” segment **of auxiliary code** * *Previous versions: `lib`, `libs`, `utils`, `helpers`* * `/api` β€” [**API segment**](https://github.com/feature-sliced/documentation/discussions/66) * *Previous versions: `api`, `service`, `requests`, `queries`* * `/config` β€” **application configuration segment** * *Previous versions: `config`, `env`, `get-env`* ### `REFINED` Low coupling[​](#refined-low-coupling "Direct link to heading") Now it is much easier to [observe the principle of low coupling](/documentation/docs/reference/slices-segments.md#zero-coupling-high-cohesion) between modules, thanks to the new layers. *At the same time, it is still recommended to avoid as much as possible cases where it is extremely difficult to "uncouple" modules* ## See also[​](#see-also "Direct link to heading") * [Notes from the report "React SPB Meetup #1"](https://t.me/feature_slices) * [React Berlin Talk - Oleg Isonen "Feature Driven Architecture"](https://www.youtube.com/watch?v=BWAeYuWFHhs) * [Comparison with v1 (community-chat)](https://t.me/feature_sliced/493) * [New ideas v2 with explanations (atomicdesign-chat)](https://t.me/atomicdesign/18708) * [Discussion of abstractions and naming for the new version of the methodology (v2)](https://github.com/feature-sliced/documentation/discussions/31) --- # Migration from v2.0 to v2.1 The main change in v2.1 is the new mental model for decomposing an interface β€” pages first. In v2.0, FSD would recommend identifying entities and features in your interface, considering even the smallest bits of entity representation and interactivity for decomposition. Then you would build widgets and pages from entities and features. In this model of decomposition, most of the logic was in entities and features, and pages were just compositional layers that didn't have much significance on their own. In v2.1, we recommend starting with pages, and possibly even stopping there. Most people already know how to separate the app into individual pages, and pages are also a common starting point when trying to locate a component in the codebase. In this new model of decomposition, you keep most of the UI and logic in each individual page, maintaining a reusable foundation in Shared. If a need arises to reuse business logic across several pages, you can move it to a layer below. Another addition to Feature-Sliced Design is the standardization of cross-imports between entities with the `@x`-notation. ## How to migrate[​](#how-to-migrate "Direct link to heading") There are no breaking changes in v2.1, which means that a project written with FSD v2.0 is also a valid project in FSD v2.1. However, we believe that the new mental model is more beneficial for teams and especially onboarding new developers, so we recommend making minor adjustments to your decomposition. ### Merge slices[​](#merge-slices "Direct link to heading") A simple way to start is by running our linter, [Steiger](https://github.com/feature-sliced/steiger), on the project. Steiger is built with the new mental model, and the most helpful rules will be: * [`insignificant-slice`](https://github.com/feature-sliced/steiger/tree/master/packages/steiger-plugin-fsd/src/insignificant-slice) β€” if an entity or feature is only used in one page, this rule will suggest merging that entity or feature into the page entirely. * [`excessive-slicing`](https://github.com/feature-sliced/steiger/tree/master/packages/steiger-plugin-fsd/src/excessive-slicing) β€” if a layer has too many slices, it's usually a sign that the decomposition is too fine-grained. This rule will suggest merging or grouping some slices to help project navigation. ``` npx steiger src ``` This will help you identify which slices are only used once, so that you could reconsider if they are really necessary. In such considerations, keep in mind that a layer forms some kind of global namespace for all the slices inside of it. Just as you wouldn't pollute the global namespace with variables that are only used once, you should treat a place in the namespace of a layer as valuable, to be used sparingly. ### Standardize cross-imports[​](#standardize-cross-imports "Direct link to heading") If you had cross-imports between in your project before (we don't judge!), you may now take advantage of a new notation for cross-importing in Feature-Sliced Design β€” the `@x`-notation. It looks like this: entities/B/some/file.ts ``` import type { EntityA } from "entities/A/@x/B"; ``` For more details, check out the [Public API for cross-imports](/documentation/docs/reference/public-api.md#public-api-for-cross-imports) section in the reference. --- # Usage with Electron Electron applications have a special architecture consisting of multiple processes with different responsibilities. Applying FSD in such a context requires adapting the structure to the Electron specifics. ``` └── src β”œβ”€β”€ app # Common app layer β”‚ β”œβ”€β”€ main # Main process β”‚ β”‚ └── index.ts # Main process entry point β”‚ β”œβ”€β”€ preload # Preload script and Context Bridge β”‚ β”‚ └── index.ts # Preload entry point β”‚ └── renderer # Renderer process β”‚ └── index.html # Renderer process entry point β”œβ”€β”€ main β”‚ β”œβ”€β”€ features β”‚ β”‚ └── user β”‚ β”‚ └── ipc β”‚ β”‚ β”œβ”€β”€ get-user.ts β”‚ β”‚ └── send-user.ts β”‚ β”œβ”€β”€ entities β”‚ └── shared β”œβ”€β”€ renderer β”‚ β”œβ”€β”€ pages β”‚ β”‚ β”œβ”€β”€ settings β”‚ β”‚ β”‚ β”œβ”€β”€ ipc β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ get-user.ts β”‚ β”‚ β”‚ β”‚ └── save-user.ts β”‚ β”‚ β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”‚ β”‚ └── user.tsx β”‚ β”‚ β”‚ └── index.ts β”‚ β”‚ └── home β”‚ β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”‚ └── home.tsx β”‚ β”‚ └── index.ts β”‚ β”œβ”€β”€ widgets β”‚ β”œβ”€β”€ features β”‚ β”œβ”€β”€ entities β”‚ └── shared └── shared # Common code between main and renderer └── ipc # IPC description (event names, contracts) ``` ## Public API rules[​](#public-api-rules "Direct link to heading") Each process must have its own public API. For example, you can't import modules from `main` to `renderer`. Only the `src/shared` folder is public for both processes. It's also necessary for describing contracts for process interaction. ## Additional changes to the standard structure[​](#additional-changes-to-the-standard-structure "Direct link to heading") It's suggested to use a new `ipc` segment, where interaction between processes takes place. The `pages` and `widgets` layers, based on their names, should not be present in `src/main`. You can use `features`, `entities` and `shared`. The `app` layer in `src` contains entry points for `main` and `renderer`, as well as the IPC. It's not desirable for segments in the `app` layer to have intersection points ## Interaction example[​](#interaction-example "Direct link to heading") src/shared/ipc/channels.ts ``` export const CHANNELS = { GET_USER_DATA: 'GET_USER_DATA', SAVE_USER: 'SAVE_USER', } as const; export type TChannelKeys = keyof typeof CHANNELS; ``` src/shared/ipc/events.ts ``` import { CHANNELS } from './channels'; export interface IEvents { [CHANNELS.GET_USER_DATA]: { args: void, response?: { name: string; email: string; }; }; [CHANNELS.SAVE_USER]: { args: { name: string; }; response: void; }; } ``` src/shared/ipc/preload.ts ``` import { CHANNELS } from './channels'; import type { IEvents } from './events'; type TOptionalArgs = T extends void ? [] : [args: T]; export type TElectronAPI = { [K in keyof typeof CHANNELS]: (...args: TOptionalArgs) => IEvents[typeof CHANNELS[K]]['response']; }; ``` src/app/preload/index.ts ``` import { contextBridge, ipcRenderer } from 'electron'; import { CHANNELS, type TElectronAPI } from 'shared/ipc'; const API: TElectronAPI = { [CHANNELS.GET_USER_DATA]: () => ipcRenderer.sendSync(CHANNELS.GET_USER_DATA), [CHANNELS.SAVE_USER]: args => ipcRenderer.invoke(CHANNELS.SAVE_USER, args), } as const; contextBridge.exposeInMainWorld('electron', API); ``` src/main/features/user/ipc/send-user.ts ``` import { ipcMain } from 'electron'; import { CHANNELS } from 'shared/ipc'; export const sendUser = () => { ipcMain.on(CHANNELS.GET_USER_DATA, ev => { ev.returnValue = { name: 'John Doe', email: 'john.doe@example.com', }; }); }; ``` src/renderer/pages/user-settings/ipc/get-user.ts ``` import { CHANNELS } from 'shared/ipc'; export const getUser = () => { const user = window.electron[CHANNELS.GET_USER_DATA](); return user ?? { name: 'John Donte', email: 'john.donte@example.com' }; }; ``` ## See also[​](#see-also "Direct link to heading") * [Process Model Documentation](https://www.electronjs.org/docs/latest/tutorial/process-model) * [Context Isolation Documentation](https://www.electronjs.org/docs/latest/tutorial/context-isolation) * [Inter-Process Communication Documentation](https://www.electronjs.org/docs/latest/tutorial/ipc) * [Example](https://github.com/feature-sliced/examples/tree/master/examples/electron) --- # Usage with Next.js FSD is compatible with Next.js in both the App Router version and the Pages Router version if you solve the main conflict β€” the `app` and `pages` folders. ## App Router[​](#app-router "Direct link to heading") ### Conflict between FSD and Next.js in the `app` layer[​](#conflict-between-fsd-and-nextjs-in-the-app-layer "Direct link to heading") Next.js suggests using the `app` folder to define application routes. It expects files in the `app` folder to correspond to pathnames. This routing mechanism **does not align** with the FSD concept, as it's not possible to maintain a flat slice structure. The solution is to move the Next.js `app` folder to the project root and import FSD pages from `src`, where the FSD layers are, into the Next.js `app` folder. You will also need to add a `pages` folder to the project root, otherwise Next.js will try to use `src/pages` as the Pages Router even if you use the App Router, which will break the build. It's also a good idea to put a `README.md` file inside this root `pages` folder describing why it is necessary, even though it's empty. ``` β”œβ”€β”€ app # App folder (Next.js) β”‚ β”œβ”€β”€ api β”‚ β”‚ └── get-example β”‚ β”‚ └── route.ts β”‚ └── example β”‚ └── page.tsx β”œβ”€β”€ pages # Empty pages folder (Next.js) β”‚ └── README.md └── src β”œβ”€β”€ app β”‚ └── api-routes # API routes β”œβ”€β”€ pages β”‚ └── example β”‚ β”œβ”€β”€ index.ts β”‚ └── ui β”‚ └── example.tsx β”œβ”€β”€ widgets β”œβ”€β”€ features β”œβ”€β”€ entities └── shared ``` Example of re-exporting a page from `src/pages` in the Next.js `app`: app/example/page.tsx ``` export { ExamplePage as default, metadata } from '@/pages/example'; ``` ### Middleware[​](#middleware "Direct link to heading") If you use middleware in your project, it must be located in the project root alongside the Next.js `app` and `pages` folders. ### Instrumentation[​](#instrumentation "Direct link to heading") The `instrumentation.js` file allows you to monitor the performance and behavior of your application. If you use it, it must be located in the project root, similar to `middleware.js`. ## Pages Router[​](#pages-router "Direct link to heading") ### Conflict between FSD and Next.js in the `pages` layer[​](#conflict-between-fsd-and-nextjs-in-the-pages-layer "Direct link to heading") Routes should be placed in the `pages` folder in the root of the project, similar to `app` folder for the App Router. The structure inside `src` where the layer folders are located remains unchanged. ``` β”œβ”€β”€ pages # Pages folder (Next.js) β”‚ β”œβ”€β”€ _app.tsx β”‚ β”œβ”€β”€ api β”‚ β”‚ └── example.ts # API route re-export β”‚ └── example β”‚ └── index.tsx └── src β”œβ”€β”€ app β”‚ β”œβ”€β”€ custom-app β”‚ β”‚ └── custom-app.tsx # Custom App component β”‚ └── api-routes β”‚ └── get-example-data.ts # API route β”œβ”€β”€ pages β”‚ └── example β”‚ β”œβ”€β”€ index.ts β”‚ └── ui β”‚ └── example.tsx β”œβ”€β”€ widgets β”œβ”€β”€ features β”œβ”€β”€ entities └── shared ``` Example of re-exporting a page from `src/pages` in the Next.js `pages`: pages/example/index.tsx ``` export { Example as default } from '@/pages/example'; ``` ### Custom `_app` component[​](#custom-_app-component "Direct link to heading") You can place your Custom App component in `src/app/_app` or `src/app/custom-app`: src/app/custom-app/custom-app.tsx ``` import type { AppProps } from 'next/app'; export const MyApp = ({ Component, pageProps }: AppProps) => { return ( <>

My Custom App component

); }; ``` pages/\_app.tsx ``` export { App as default } from '@/app/custom-app'; ``` ## Route Handlers (API routes)[​](#route-handlers-api-routes "Direct link to heading") Use the `api-routes` segment in the `app` layer to work with Route Handlers. Be mindful when writing backend code in the FSD structure β€” FSD is primarily intended for frontends, meaning that's what people will expect to find. If you need a lot of endpoints, consider separating them into a different package in a monorepo. * App Router * Pages Router src/app/api-routes/get-example-data.ts ``` import { getExamplesList } from '@/shared/db'; export const getExampleData = () => { try { const examplesList = getExamplesList(); return Response.json({ examplesList }); } catch { return Response.json(null, { status: 500, statusText: 'Ouch, something went wrong', }); } }; ``` app/api/example/route.ts ``` export { getExampleData as GET } from '@/app/api-routes'; ``` src/app/api-routes/get-example-data.ts ``` import type { NextApiRequest, NextApiResponse } from 'next'; const config = { api: { bodyParser: { sizeLimit: '1mb', }, }, maxDuration: 5, }; const handler = (req: NextApiRequest, res: NextApiResponse) => { res.status(200).json({ message: 'Hello from FSD' }); }; export const getExampleData = { config, handler } as const; ``` src/app/api-routes/index.ts ``` export { getExampleData } from './get-example-data'; ``` app/api/example.ts ``` import { getExampleData } from '@/app/api-routes'; export const config = getExampleData.config; export default getExampleData.handler; ``` ## Additional recommendations[​](#additional-recommendations "Direct link to heading") * Use the `db` segment in the `shared` layer to describe database queries and their further use in higher layers. * Caching and revalidating queries logic is better kept in the same place as the queries themselves. ## See also[​](#see-also "Direct link to heading") * [Next.js Project Structure](https://nextjs.org/docs/app/getting-started/project-structure) * [Next.js Page Layouts](https://nextjs.org/docs/app/getting-started/layouts-and-pages) --- # Usage with NuxtJS It is possible to implement FSD in a NuxtJS project, but conflicts arise due to the differences between NuxtJS project structure requirements and FSD principles: * Initially, NuxtJS offers a project file structure without a `src` folder, i.e. in the root of the project. * The file routing is in the `pages` folder, while in FSD this folder is reserved for the flat slice structure. ## Adding an alias for the `src` directory[​](#adding-an-alias-for-the-src-directory "Direct link to heading") Add an `alias` object to your config: nuxt.config.ts ``` export default defineNuxtConfig({ devtools: { enabled: true }, // Not FSD related, enabled at project startup alias: { "@": '../src' }, }) ``` ## Choose how to configure the router[​](#choose-how-to-configure-the-router "Direct link to heading") In NuxtJS, there are two ways to customize the routing - using a config and using a file structure. In the case of file-based routing, you will create index.vue files in folders inside the app/routes directory, and in the case of configure, you will configure the routers in the `router.options.ts` file. ### Routing using config[​](#routing-using-config "Direct link to heading") In the `app` layer, create a `router.options.ts` file, and export a config object from it: app/router.options.ts ``` import type { RouterConfig } from '@nuxt/schema'; export default { routes: (_routes) => [], }; ``` To add a `Home` page to your project, you need to do the following steps: * Add a page slice inside the `pages` layer * Add the appropriate route to the `app/router.config.ts` config To create a page slice, let's use the [CLI](https://github.com/feature-sliced/cli): ``` fsd pages home ``` Create a `home-page.vue` file inside the ui segment, access it using the Public API src/pages/home/index.ts ``` export { default as HomePage } from './ui/home-page'; ``` Thus, the file structure will look like this: ``` |── src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ router.config.ts β”‚ β”œβ”€β”€ pages β”‚ β”‚ β”œβ”€β”€ home β”‚ β”‚ β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ home-page.vue β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts ``` Finally, let's add a route to the config: app/router.config.ts ``` import type { RouterConfig } from '@nuxt/schema' export default { routes: (_routes) => [ { name: 'home', path: '/', component: () => import('@/pages/home.vue').then(r => r.default || r) } ], } ``` ### File Routing[​](#file-routing "Direct link to heading") First of all, create a `src` directory in the root of your project, and create app and pages layers inside this directory and a routes folder inside the app layer. Thus, your file structure should look like this: ``` β”œβ”€β”€ src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ routes β”‚ β”œβ”€β”€ pages # Pages folder, related to FSD ``` In order for NuxtJS to use the routes folder inside the `app` layer for file routing, you need to modify `nuxt.config.ts` as follows: nuxt.config.ts ``` export default defineNuxtConfig({ devtools: { enabled: true }, // Not FSD related, enabled at project startup alias: { "@": '../src' }, dir: { pages: './src/app/routes' } }) ``` Now, you can create routes for pages within `app` and connect pages from `pages` to them. For example, to add a `Home` page to your project, you need to do the following steps: * Add a page slice inside the `pages` layer * Add the corresponding route inside the `app` layer * Connect the page from the slice with the route To create a page slice, let's use the [CLI](https://github.com/feature-sliced/cli): ``` fsd pages home ``` Create a `home-page.vue` file inside the ui segment, access it using the Public API src/pages/home/index.ts ``` export { default as HomePage } from './ui/home-page'; ``` Create a route for this page inside the `app` layer: ``` β”œβ”€β”€ src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ routes β”‚ β”‚ β”‚ β”œβ”€β”€ index.vue β”‚ β”œβ”€β”€ pages β”‚ β”‚ β”œβ”€β”€ home β”‚ β”‚ β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ home-page.vue β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts ``` Add your page component inside the `index.vue` file: src/app/routes/index.vue ``` ``` ## What to do with `layouts`?[​](#what-to-do-with-layouts "Direct link to heading") You can place layouts inside the `app` layer, to do this you need to modify the config as follows: nuxt.config.ts ``` export default defineNuxtConfig({ devtools: { enabled: true }, // Not related to FSD, enabled at project startup alias: { "@": '../src' }, dir: { pages: './src/app/routes', layouts: './src/app/layouts' } }) ``` ## See also[​](#see-also "Direct link to heading") * [Documentation on changing directory config in NuxtJS](https://nuxt.com/docs/api/nuxt-config#dir) * [Documentation on changing router config in NuxtJS](https://nuxt.com/docs/guide/recipes/custom-routing#router-config) * [Documentation on changing aliases in NuxtJS](https://nuxt.com/docs/api/nuxt-config#alias) --- # Usage with React Query ## The problem of β€œwhere to put the keys”[​](#the-problem-of-where-to-put-the-keys "Direct link to heading") ### Solution β€” break down by entities[​](#solution--break-down-by-entities "Direct link to heading") If the project already has a division into entities, and each request corresponds to a single entity, the purest division will be by entity. In this case, we suggest using the following structure: ``` └── src/ # β”œβ”€β”€ app/ # | ... # β”œβ”€β”€ pages/ # | ... # β”œβ”€β”€ entities/ # | β”œβ”€β”€ {entity}/ # | ... └── api/ # | β”œβ”€β”€ `{entity}.query` # Query-factory where are the keys and functions | β”œβ”€β”€ `get-{entity}` # Entity getter function | β”œβ”€β”€ `create-{entity}` # Entity creation function | β”œβ”€β”€ `update-{entity}` # Entity update function | β”œβ”€β”€ `delete-{entity}` # Entity delete function | ... # | # β”œβ”€β”€ features/ # | ... # β”œβ”€β”€ widgets/ # | ... # └── shared/ # ... # ``` If there are connections between the entities (for example, the Country entity has a field-list of City entities), then you can use the [public API for cross-imports](/documentation/docs/reference/public-api.md#public-api-for-cross-imports) or consider the alternative solution below. ### Alternative solution β€” keep it in shared[​](#alternative-solution--keep-it-in-shared "Direct link to heading") In cases where entity separation is not appropriate, the following structure can be considered: ``` └── src/ # ... # └── shared/ # β”œβ”€β”€ api/ # ... β”œβ”€β”€ `queries` # Query-factories | β”œβ”€β”€ `document.ts` # | β”œβ”€β”€ `background-jobs.ts` # | ... # └── index.ts # ``` Then in `@/shared/api/index.ts`: @/shared/api/index.ts ``` export { documentQueries } from "./queries/document"; ``` ## The problem of β€œWhere to insert mutations?”[​](#the-problem-of-where-to-insert-mutations "Direct link to heading") It is not recommended to mix mutations with queries. There are two options: ### 1. Define a custom hook in the `api` segment near the place of use[​](#1-define-a-custom-hook-in-the-api-segment-near-the-place-of-use "Direct link to heading") @/features/update-post/api/use-update-title.ts ``` export const useUpdateTitle = () => { const queryClient = useQueryClient(); return useMutation({ mutationFn: ({ id, newTitle }) => apiClient .patch(`/posts/${id}`, { title: newTitle }) .then((data) => console.log(data)), onSuccess: (newPost) => { queryClient.setQueryData(postsQueries.ids(id), newPost); }, }); }; ``` ### 2. Define a mutation function somewhere else (Shared or Entities) and use `useMutation` directly in the component[​](#2-define-a-mutation-function-somewhere-else-shared-or-entities-and-use-usemutation-directly-in-the-component "Direct link to heading") ``` const { mutateAsync, isPending } = useMutation({ mutationFn: postApi.createPost, }); ``` @/pages/post-create/ui/post-create-page.tsx ``` export const CreatePost = () => { const { classes } = useStyles(); const [title, setTitle] = useState(""); const { mutate, isPending } = useMutation({ mutationFn: postApi.createPost, }); const handleChange = (e: ChangeEvent) => setTitle(e.target.value); const handleSubmit = (e: FormEvent) => { e.preventDefault(); mutate({ title, userId: DEFAULT_USER_ID }); }; return (
Create ); }; ``` ## Organization of requests[​](#organization-of-requests "Direct link to heading") ### Query factory[​](#query-factory "Direct link to heading") A query factory is an object where the key values are functions that return a list of query keys. Here's how to use it: ``` const keyFactory = { all: () => ["entity"], lists: () => [...postQueries.all(), "list"], }; ``` info `queryOptions` is a built-in utility in react-query\@v5 (optional) ``` queryOptions({ queryKey, ...options, }); ``` For greater type safety, further compatibility with future versions of react-query, and easy access to functions and query keys, you can use the built-in queryOptions function from β€œ@tanstack/react-query” [(More details here)](https://tkdodo.eu/blog/the-query-options-api#queryoptions). ### 1. Creating a Query Factory[​](#1-creating-a-query-factory "Direct link to heading") @/entities/post/api/post.queries.ts ``` import { keepPreviousData, queryOptions } from "@tanstack/react-query"; import { getPosts } from "./get-posts"; import { getDetailPost } from "./get-detail-post"; import { PostDetailQuery } from "./query/post.query"; export const postQueries = { all: () => ["posts"], lists: () => [...postQueries.all(), "list"], list: (page: number, limit: number) => queryOptions({ queryKey: [...postQueries.lists(), page, limit], queryFn: () => getPosts(page, limit), placeholderData: keepPreviousData, }), details: () => [...postQueries.all(), "detail"], detail: (query?: PostDetailQuery) => queryOptions({ queryKey: [...postQueries.details(), query?.id], queryFn: () => getDetailPost({ id: query?.id }), staleTime: 5000, }), }; ``` ### 2. Using Query Factory in application code[​](#2-using-query-factory-in-application-code "Direct link to heading") ``` import { useParams } from "react-router-dom"; import { postApi } from "@/entities/post"; import { useQuery } from "@tanstack/react-query"; type Params = { postId: string; }; export const PostPage = () => { const { postId } = useParams(); const id = parseInt(postId || ""); const { data: post, error, isLoading, isError, } = useQuery(postApi.postQueries.detail({ id })); if (isLoading) { return
Loading...
; } if (isError || !post) { return <>{error?.message}; } return (

Post id: {post.id}

{post.title}

{post.body}

Owner: {post.userId}
); }; ``` ### Benefits of using a Query Factory[​](#benefits-of-using-a-query-factory "Direct link to heading") * **Request structuring:** A factory allows you to organize all API requests in one place, making your code more readable and maintainable. * **Convenient access to queries and keys:** The factory provides convenient methods for accessing different types of queries and their keys. * **Query Refetching Ability:** The factory allows easy refetching without the need to change query keys in different parts of the application. ## Pagination[​](#pagination "Direct link to heading") In this section, we'll look at an example of the `getPosts` function, which makes an API request to retrieve post entities using pagination. ### 1. Creating a function `getPosts`[​](#1-creating-a-function-getposts "Direct link to heading") The getPosts function is located in the `get-posts.ts` file, which is located in the `api` segment @/pages/post-feed/api/get-posts.ts ``` import { apiClient } from "@/shared/api/base"; import { PostWithPaginationDto } from "./dto/post-with-pagination.dto"; import { PostQuery } from "./query/post.query"; import { mapPost } from "./mapper/map-post"; import { PostWithPagination } from "../model/post-with-pagination"; const calculatePostPage = (totalCount: number, limit: number) => Math.floor(totalCount / limit); export const getPosts = async ( page: number, limit: number, ): Promise => { const skip = page * limit; const query: PostQuery = { skip, limit }; const result = await apiClient.get("/posts", query); return { posts: result.posts.map((post) => mapPost(post)), limit: result.limit, skip: result.skip, total: result.total, totalPages: calculatePostPage(result.total, limit), }; }; ``` ### 2. Query factory for pagination[​](#2-query-factory-for-pagination "Direct link to heading") The `postQueries` query factory defines various query options for working with posts, including requesting a list of posts with a specific page and limit. ``` import { keepPreviousData, queryOptions } from "@tanstack/react-query"; import { getPosts } from "./get-posts"; export const postQueries = { all: () => ["posts"], lists: () => [...postQueries.all(), "list"], list: (page: number, limit: number) => queryOptions({ queryKey: [...postQueries.lists(), page, limit], queryFn: () => getPosts(page, limit), placeholderData: keepPreviousData, }), }; ``` ### 3. Use in application code[​](#3-use-in-application-code "Direct link to heading") @/pages/home/ui/index.tsx ``` export const HomePage = () => { const itemsOnScreen = DEFAULT_ITEMS_ON_SCREEN; const [page, setPage] = usePageParam(DEFAULT_PAGE); const { data, isFetching, isLoading } = useQuery( postApi.postQueries.list(page, itemsOnScreen), ); return ( <> setPage(page)} page={page} count={data?.totalPages} variant="outlined" color="primary" /> ); }; ``` note The example is simplified, the full version is available on [GitHub](https://github.com/ruslan4432013/fsd-react-query-example) ## `QueryProvider` for managing queries[​](#queryprovider-for-managing-queries "Direct link to heading") In this guide, we will look at how to organize a `QueryProvider`. ### 1. Creating a `QueryProvider`[​](#1-creating-a-queryprovider "Direct link to heading") The file `query-provider.tsx` is located at the path `@/app/providers/query-provider.tsx`. @/app/providers/query-provider.tsx ``` import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { ReactNode } from "react"; type Props = { children: ReactNode; client: QueryClient; }; export const QueryProvider = ({ client, children }: Props) => { return ( {children} ); }; ``` ### 2. Creating a `QueryClient`[​](#2-creating-a-queryclient "Direct link to heading") `QueryClient` is an instance used to manage API requests. The `query-client.ts` file is located at `@/shared/api/query-client.ts`. `QueryClient` is created with certain settings for query caching. @/shared/api/query-client.ts ``` import { QueryClient } from "@tanstack/react-query"; export const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, gcTime: 5 * 60 * 1000, }, }, }); ``` ## Code generation[​](#code-generation "Direct link to heading") There are tools that can generate API code for you, but they are less flexible than the manual approach described above. If your Swagger file is well-structured, and you're using one of these tools, it might make sense to generate all the code in the `@/shared/api` directory. ## Additional advice for organizing RQ[​](#additional-advice-for-organizing-rq "Direct link to heading") ### API Client[​](#api-client "Direct link to heading") Using a custom API client class in the shared layer, you can standardize the configuration and work with the API in the project. This allows you to manage logging, headers and data exchange format (such as JSON or XML) from one place. This approach makes it easier to maintain and develop the project because it simplifies changes and updates to interactions with the API. @/shared/api/api-client.ts ``` import { API_URL } from "@/shared/config"; export class ApiClient { private baseUrl: string; constructor(url: string) { this.baseUrl = url; } async handleResponse(response: Response): Promise { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } try { return await response.json(); } catch (error) { throw new Error("Error parsing JSON response"); } } public async get( endpoint: string, queryParams?: Record, ): Promise { const url = new URL(endpoint, this.baseUrl); if (queryParams) { Object.entries(queryParams).forEach(([key, value]) => { url.searchParams.append(key, value.toString()); }); } const response = await fetch(url.toString(), { method: "GET", headers: { "Content-Type": "application/json", }, }); return this.handleResponse(response); } public async post>( endpoint: string, body: TData, ): Promise { const response = await fetch(`${this.baseUrl}${endpoint}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }); return this.handleResponse(response); } } export const apiClient = new ApiClient(API_URL); ``` ## See also[​](#see-also "Direct link to heading") * [(GitHub) Sample Project](https://github.com/ruslan4432013/fsd-react-query-example) * [(CodeSandbox) Sample Project](https://codesandbox.io/p/github/ruslan4432013/fsd-react-query-example/main) * [About the query factory](https://tkdodo.eu/blog/the-query-options-api) --- # Usage with SvelteKit It is possible to implement FSD in a SvelteKit project, but conflicts arise due to the differences between the structure requirements of a SvelteKit project and the principles of FSD: * Initially, SvelteKit offers a file structure inside the `src/routes` folder, while in FSD the routing must be part of the `app` layer. * SvelteKit suggests putting everything not related to routing in the `src/lib` folder. ## Let's set up the config[​](#lets-set-up-the-config "Direct link to heading") svelte.config.ts ``` import adapter from '@sveltejs/adapter-auto'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config}*/ const config = { preprocess: [vitePreprocess()], kit: { adapter: adapter(), files: { routes: 'src/app/routes', // move routing inside the app layer lib: 'src', appTemplate: 'src/app/index.html', // Move the application entry point inside the app layer assets: 'public' }, alias: { '@/*': 'src/*' // Create an alias for the src directory } } }; export default config; ``` ## Move file routing to `src/app`.[​](#move-file-routing-to-srcapp "Direct link to heading") Let's create an app layer, move the app's entry point `index.html` into it, and create a routes folder. Thus, your file structure should look like this: ``` β”œβ”€β”€ src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ index.html β”‚ β”‚ β”œβ”€β”€ routes β”‚ β”œβ”€β”€ pages # FSD Pages folder ``` Now, you can create routes for pages within `app` and connect pages from `pages` to them. For example, to add a home page to your project, you need to do the following steps: * Add a page slice inside the `pages` layer * Add the corresponding rooute to the `routes` folder from the `app` layer * Align the page from the slice with the rooute To create a page slice, let's use the [CLI](https://github.com/feature-sliced/cli): ``` fsd pages home ``` Create a `home-page.svelte` file inside the ui segment, access it using the Public API src/pages/home/index.ts ``` export { default as HomePage } from './ui/home-page.svelte'; ``` Create a route for this page inside the `app` layer: ``` β”œβ”€β”€ src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ routes β”‚ β”‚ β”‚ β”œβ”€β”€ +page.svelte β”‚ β”‚ β”œβ”€β”€ index.html β”‚ β”œβ”€β”€ pages β”‚ β”‚ β”œβ”€β”€ home β”‚ β”‚ β”‚ β”œβ”€β”€ ui β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ home-page.svelte β”‚ β”‚ β”‚ β”œβ”€β”€ index.ts ``` Add your page component inside the `+page.svelte` file: src/app/routes/+page.svelte ``` ``` ## See also.[​](#see-also "Direct link to heading") * [Documentation on changing directory config in SvelteKit](https://kit.svelte.dev/docs/configuration#files) --- # Docs for LLMs This page provides links and guidance for LLM crawlers. * Spec: ### Files[​](#files "Direct link to heading") * [llms.txt](/documentation/llms.txt) * [llms-full.txt](/documentation/llms-full.txt) ### Notes[​](#notes "Direct link to heading") * Files are served from the site root, regardless of the current page path. * In deployments with a non-root base URL (e.g., `/documentation/`), the links above are automatically prefixed. --- # Layers Layers are the first level of organisational hierarchy in Feature-Sliced Design. Their purpose is to separate code based on how much responsibility it needs and how many other modules in the app it depends on. Every layer carries special semantic meaning to help you determine how much responsibility you should allocate to your code. There are **7 layers** in total, arranged from most responsibility andΒ dependency to least: ![A file system tree, with a single root folder called src and then seven subfolders: app, processes, pages, widgets, features, entities, shared. The processes folder is slightly faded out.](/documentation/img/layers/folders-graphic-light.svg#light-mode-only) ![A file system tree, with a single root folder called src and then seven subfolders: app, processes, pages, widgets, features, entities, shared. The processes folder is slightly faded out.](/documentation/img/layers/folders-graphic-dark.svg#dark-mode-only) 1. App 2. Processes (deprecated) 3. Pages 4. Widgets 5. Features 6. Entities 7. Shared You don't have to use every layer in your project β€” only add them if you think it brings value to your project. Typically, most frontend projects will have at least the Shared, Pages, and App layers. In practice, layers are folders with lowercase names (for example, `πŸ“ shared`, `πŸ“ pages`, `πŸ“ app`). Adding new layers is *not recommended* because their semantics are standardized. ## Import rule on layers[​](#import-rule-on-layers "Direct link to heading") Layers are made up of *slices* β€” highly cohesive groups of modules. Dependencies between slices are regulated by **the import rule on layers**: > *A module (file) in a slice can only import other slices when they are located on layers strictly below.* For example, the folder `πŸ“ ~/features/aaa` is a slice with the name "aaa". A file inside of it, `~/features/aaa/api/request.ts`, cannot import code from any file in `πŸ“ ~/features/bbb`, but can import code from `πŸ“ ~/entities` and `πŸ“ ~/shared`, as well as any sibling code from `πŸ“ ~/features/aaa`, for example, `~/features/aaa/lib/cache.ts`. Layers App and Shared are **exceptions** to this rule β€” they are both a layer and a slice at the same time. Slices partition code by business domain, and these two layers are exceptions because Shared does not have business domains, and App combines all business domains. In practice, this means that layers App and Shared are made up of segments, and segments can import each other freely. ## Layer definitions[​](#layer-definitions "Direct link to heading") This section describes the semantic meaning of each layer to create an intuition for what kind of code belongs there. ### Shared[​](#shared "Direct link to heading") This layer forms a foundation for the rest of the app. It's a place to create connections with the external world, for example, backends, third-party libraries, the environment. It is also a place to define your own highly contained libraries. This layer, like the App layer, *does not contain slices*. Slices are intended to divide the layer into business domains, but business domains do not exist in Shared. This means that all files in Shared can reference and import from each other. Here are the segments that you can typically find in this layer: * `πŸ“ api` β€” the API client and potentially also functions to make requests to specific backend endpoints. * `πŸ“ ui` β€” the application's UI kit.
Components on this layer should not contain business logic, but it's okay for them to be business-themed. For example, you can put the company logo and page layout here. Components with UI logic are also allowed (for example, autocomplete or a search bar). * `πŸ“ lib` β€” a collection of internal libraries.
This folder should not be treated as helpers or utilities ([read here why these folders often turn into a dump](https://dev.to/sergeysova/why-utils-helpers-is-a-dump-45fo)). Instead, every library in this folder should have one area of focus, for example, dates, colors, text manipulation, etc. That area of focus should be documented in a README file. The developers in your team should know what can and cannot be added to these libraries. * `πŸ“ config` β€” environment variables, global feature flags and other global configuration for your app. * `πŸ“ routes` β€” route constants or patterns for matching routes. * `πŸ“ i18n` β€” setup code for translations, global translation strings. You are free to add more segments, but make sure that the name of these segments describes the purpose of the content, not its essence. For example, `components`, `hooks`, and `types` are bad segment names because they aren't that helpful when you're looking for code. ### Entities[​](#entities "Direct link to heading") Slices on this layer represent concepts from the real world that the project is working with. Commonly, they are the terms that the business uses to describe the product. For example, a social network might work with business entities like User, Post, and Group. An entity slice might contain the data storage (`πŸ“ model`), data validation schemas (`πŸ“ model`), entity-related API request functions (`πŸ“ api`), as well as the visual representation of this entity in the interface (`πŸ“ ui`). The visual representation doesn't have to produce a complete UI block β€” it is primarily meant to reuse the same appearance across several pages in the app, and different business logic may be attached to it through props or slots. #### Entity relationships[​](#entity-relationships "Direct link to heading") Entities in FSD are slices, and by default, slices cannot know about each other. In real life, however, entities often interact with each other, and sometimes one entity owns or contains other entities. Because of that, the business logic of these interactions is preferably kept in higher layers, like Features or Pages. When one entity's data object contains other data objects, usually it's a good idea to make the connection between the entities explicit and side-step the slice isolation by making a cross-reference API with the `@x` notation. The reason is that connected entities need to be refactored together, so it's best to make the connection impossible to miss. For example: entities/artist/model/artist.ts ``` import type { Song } from "entities/song/@x/artist"; export interface Artist { name: string; songs: Array; } ``` entities/song/@x/artist.ts ``` export type { Song } from "../model/song.ts"; ``` Learn more about the `@x` notation in the [Public API for cross-imports](/documentation/docs/reference/public-api.md#public-api-for-cross-imports) section. ### Features[​](#features "Direct link to heading") This layer is for the main interactions in your app, things that your users care to do. These interactions often involve business entities, because that's what the app is about. A crucial principle for using the Features layer effectively is: **not everything needs to be a feature**. A good indicator that something needs to be a feature is the fact that it is reused on several pages. For example, if the app has several editors, and all of them have comments, then comments are a reused feature. Remember that slices are a mechanism for finding code quickly, and if there are too many features, the important ones are drowned out. Ideally, when you arrive in a new project, you would discover its functionality by looking through the pages and features. When deciding on what should be a feature, optimize for the experience of a newcomer to the project to quickly discover large important areas of code. A feature slice might contain the UI to perform the interaction like a form (`πŸ“ ui`), the API calls needed to make the action (`πŸ“ api`), validation and internal state (`πŸ“ model`), feature flags (`πŸ“ config`). ### Widgets[​](#widgets "Direct link to heading") The Widgets layer is intended for large self-sufficient blocks of UI. Widgets are most useful when they are reused across multiple pages, or when the page that they belong to has multiple large independent blocks, and this is one of them. If a block of UI makes up most of the interesting content on a page, and is never reused, it **should not be a widget**, and instead it should be placed directly inside that page. tip If you're using a nested routing system (like the router of [Remix](https://remix.run)), it may be helpful to use the Widgets layer in the same way as a flat routing system would use the Pages layer β€” to create full router blocks, complete with related data fetching, loading states, and error boundaries. In the same way, you can store page layouts on this layer. ### Pages[​](#pages "Direct link to heading") Pages are what makes up websites and applications (also known as screens or activities). One page usually corresponds to one slice, however, if there are several very similar pages, they can be grouped into one slice, for example, registration and login forms. There's no limit to how much code you can place in a page slice as long as your team still finds it easy to navigate. If a UI block on a page is not reused, it's perfectly fine to keep it inside the page slice. In a page slice you can typically find the page's UI as well as loading states and error boundaries (`πŸ“ ui`) and the data fetching and mutating requests (`πŸ“ api`). It's not common for a page to have a dedicated data model, and tiny bits of state can be kept in the components themselves. ### Processes[​](#processes "Direct link to heading") caution This layer has been deprecated. The current version of the spec recommends avoiding it and moving its contents to `features` and `app` instead. Processes are escape hatches for multi-page interactions. This layer is deliberately left undefined. Most applications should not use this layer, and keep router-level and server-level logic on the App layer. Consider using this layer only when the App layer grows large enough to become unmaintainable and needs unloading. ### App[​](#app "Direct link to heading") All kinds of app-wide matters, both in the technical sense (e.g., context providers) and in the business sense (e.g., analytics). This layer usually doesn't contain slices, as well as Shared, instead having segments directly. Here are the segments that you can typically find in this layer: * `πŸ“ routes` β€” the router configuration * `πŸ“ store` β€” global store configuration * `πŸ“ styles` β€” global styles * `πŸ“ entrypoint` β€” the entrypoint to the application code, framework-specific --- # Public API A public API is a *contract* between a group of modules, like a slice, and the code that uses it. It also acts as a gate, only allowing access to certain objects, and only through that public API. In practice, it's usually implemented as an index file with re-exports: pages/auth/index.js ``` export { LoginPage } from "./ui/LoginPage"; export { RegisterPage } from "./ui/RegisterPage"; ``` ## What makes a good public API?[​](#what-makes-a-good-public-api "Direct link to heading") A good public API makes using and integrating into other code a slice convenient and reliable. It can be achieved by setting these three goals: 1. The rest of the application must be protected from structural changes to the slice, like a refactoring 2. Significant changes in the behavior of the slice that break the previous expectations should cause changes in the public API 3. Only the necessary parts of the slice should be exposed The last goal has some important practical implications. It may be tempting to create wildcard re-exports of everything, especially in early development of the slice, because any new objects you export from your files are also automatically exported from the slice: Bad practice, features/comments/index.js ``` // ❌ BAD CODE BELOW, DON'T DO THIS export * from "./ui/Comment"; // πŸ‘Ž don't try this at home export * from "./model/comments"; // πŸ’© this is bad practice ``` This hurts the discoverability of a slice because you can't easily tell what the interface of this slice is. Not knowing the interface means that you have to dig deep into the code of a slice to understand how to integrate it. Another problem is that you might accidentally expose the module internals, which will make refactoring difficult if someone starts depending on them. ## Public API for cross-imports[​](#public-api-for-cross-imports "Direct link to heading") Cross-imports are a situation when one slice imports from another slice on the same layer. Usually that is prohibited by the [import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers), but often there are legitimate reasons to cross-import. For example, business entities often reference each other in the real world, and it's best to reflect these relationships in the code instead of working around them. For this purpose, there's a special kind of public API, also known as the `@x`-notation. If you have entities A and B, and entity B needs to import from entity A, then entity A can declare a separate public API just for entity B. * `πŸ“‚ entities` * `πŸ“‚ A` * `πŸ“‚ @x` * `πŸ“„ B.ts` β€” a special public API just for code inside `entities/B/` * `πŸ“„ index.ts` β€” the regular public API Then the code inside `entities/B/` can import from `entities/A/@x/B`: ``` import type { EntityA } from "entities/A/@x/B"; ``` The notation `A/@x/B` is meant to be read as "A crossed with B". note Try to keep cross-imports to a minimum, and **only use this notation on the Entities layer**, where eliminating cross-imports is often unreasonable. ## Issues with index files[​](#issues-with-index-files "Direct link to heading") Index files like `index.js`, also known as barrel files, are the most common way to define a public API. They are easy to make, but they are known to cause problems with certain bundlers and frameworks. ### Circular imports[​](#circular-imports "Direct link to heading") Circular import is when two or more files import each other in a circle. ![Three files importing each other in a circle](/documentation/img/circular-import-light.svg#light-mode-only)![Three files importing each other in a circle](/documentation/img/circular-import-dark.svg#dark-mode-only) Pictured above: three files, `fileA.js`, `fileB.js`, and `fileC.js`, importing each other in a circle. These situations are often difficult for bundlers to deal with, and in some cases they might even lead to runtime errors that might be difficult to debug. Circular imports can occur without index files, but having an index file presents a clear opportunity to accidentally create a circular import. It often happens when you have two objects exposed in the public API of a slice, for example, `HomePage` and `loadUserStatistics`, and the `HomePage` needs to access `loadUserStatistics`, but it does it like this: pages/home/ui/HomePage.jsx ``` import { loadUserStatistics } from "../"; // importing from pages/home/index.js export function HomePage() { /* … */ } ``` pages/home/index.js ``` export { HomePage } from "./ui/HomePage"; export { loadUserStatistics } from "./api/loadUserStatistics"; ``` This situation creates a circular import, because `index.js` imports `ui/HomePage.jsx`, but `ui/HomePage.jsx` imports `index.js`. To prevent this issue, consider these two principles. If you have two files, and one imports from the other: * When they are in the same slice, always use *relative* imports and write the full import path * When they are in different slices, always use *absolute* imports, for example, with an alias ### Large bundles and broken tree-shaking in Shared[​](#large-bundles "Direct link to heading") Some bundlers might have a hard time tree-shaking (removing code that isn't imported) when you have an index file that re-exports everything. Usually this isn't a problem for public APIs, because the contents of a module are usually quite closely related, so you would rarely need to import one thing and tree-shake away the other. However, there are two very common cases when the normal rules of public API in FSD may lead to issues β€” `shared/ui` and `shared/lib`. These two folders are both collections of unrelated things that often aren't all needed in one place. For example, `shared/ui` might have modules for every component in the UI library: * `πŸ“‚ shared/ui/` * `πŸ“ button` * `πŸ“ text-field` * `πŸ“ carousel` * `πŸ“ accordion` This problem is made worse when one of these modules has a heavy dependency, like a syntax highlighter or a drag'n'drop library. You don't want to pull those into every page that uses something from `shared/ui`, for example, a button. If your bundles grow undesirably due to a single public API in `shared/ui` or `shared/lib`, it's recommended to instead have a separate index file for each component or library: * `πŸ“‚ shared/ui/` * `πŸ“‚ button` * `πŸ“„ index.js` * `πŸ“‚ text-field` * `πŸ“„ index.js` Then the consumers of these components can import them directly like this: pages/sign-in/ui/SignInPage.jsx ``` import { Button } from '@/shared/ui/button'; import { TextField } from '@/shared/ui/text-field'; ``` ### No real protection against side-stepping the public API[​](#no-real-protection-against-side-stepping-the-public-api "Direct link to heading") When you create an index file for a slice, you don't actually forbid anyone from not using it and importing directly. This is especially a problem for auto-imports, because there are several places from which an object can be imported, so the IDE has to decide that for you. Sometimes it might choose to import directly, breaking the public API rule on slices. To catch these issues automatically, we recommend using [Steiger](https://github.com/feature-sliced/steiger), an architectural linter with a ruleset for Feature-Sliced Design. ### Worse performance of bundlers on large projects[​](#worse-performance-of-bundlers-on-large-projects "Direct link to heading") Having a large amount of index files in a project can slow down the development server, as noted by TkDodo in [his article "Please Stop Using Barrel Files"](https://tkdodo.eu/blog/please-stop-using-barrel-files). There are several things you can do to tackle this issue: 1. The same advice as in ["Large bundles and broken tree-shaking in Shared" issue](#large-bundles) β€” have separate index files for each component/library in `shared/ui` and `shared/lib` instead of one big one 2. Avoid having index files in segments on layers that have slices.
For example, if you have an index for the feature "comments", `πŸ“„ features/comments/index.js`, there's no reason to have another index for the `ui` segment of that feature, `πŸ“„ features/comments/ui/index.js`. 3. If you have a very big project, there's a good chance that your application can be split into several big chunks.
For example, Google Docs has very different responsibilities for the document editor and for the file browser. You can create a monorepo setup where each package is a separate FSD root, with its own set of layers. Some packages can only have the Shared and Entities layers, others might only have Pages and App, others still might include their own small Shared, but still use the big one from another package too. --- # Slices and segments ## Slices[​](#slices "Direct link to heading") Slices are the second level in the organizational hierarchy of Feature-Sliced Design. Their main purpose is to group code by its meaning for the product, business, or just the application. The names of slices are not standardized because they are directly determined by the business domain of your application. For example, a photo gallery might have slices `photo`, `effects`, `gallery-page`. A social network would require different slices, for example, `post`, `comments`, `news-feed`. The layers Shared and App don't contain slices. That is because Shared should contain no business logic at all, hence has no meaning for the product, and App should contain only code that concerns the entire application, so no splitting is necessary. ### Zero coupling and high cohesion[​](#zero-coupling-high-cohesion "Direct link to heading") Slices are meant to be independent and highly cohesive groups of code files. The graphic below might help to visualize the tricky concepts of *cohesion* and *coupling*: ![](/documentation/img/coupling-cohesion-light.svg#light-mode-only)![](/documentation/img/coupling-cohesion-dark.svg#dark-mode-only) Image inspired by An ideal slice is independent from other slices on its layer (zero coupling) and contains most of the code related to its primary goal (high cohesion). The independence of slices is enforced by the [import rule on layers](/documentation/docs/reference/layers.md#import-rule-on-layers): > *A module (file) in a slice can only import other slices when they are located on layers strictly below.* ### Public API rule on slices[​](#public-api-rule-on-slices "Direct link to heading") Inside a slice, the code could be organized in any way that you want. That doesn't pose any issues as long as the slice provides a good public API for other slices to use it. This is enforced with the **public API rule on slices**: > *Every slice (and segment on layers that don't have slices) must contain a public API definition.* > > *Modules outside of this slice/segment can only reference the public API, not the internal file structure of the slice/segment.* Read more about the rationale of public APIs and the best practices on creating one in the [Public API reference](/documentation/docs/reference/public-api.md). ### Slice groups[​](#slice-groups "Direct link to heading") Closely related slices can be structurally grouped in a folder, but they should exercise the same isolation rules as other slices β€” there should be **no code sharing** in that folder. ![Features \"compose\", \"like\" and \"delete\" grouped in a folder \"post\". In that folder there is also a file \"some-shared-code.ts\" that is crossed out to imply that it\'s not allowed.](/documentation/assets/images/graphic-nested-slices-b9c44e6cc55ecdbf3e50bf40a61e5a27.svg) ## Segments[​](#segments "Direct link to heading") Segments are the third and final level in the organizational hierarchy, and their purpose is to group code by its technical nature. There a few standardized segment names: * `ui` β€” everything related to UI display: UI components, date formatters, styles, etc. * `api` β€” backend interactions: request functions, data types, mappers, etc. * `model` β€” the data model: schemas, interfaces, stores, and business logic. * `lib` β€” library code that other modules on this slice need. * `config` β€” configuration files and feature flags. See the [Layers page](/documentation/docs/reference/layers.md#layer-definitions) for examples of what each of these segments might be used for on different layers. You can also create custom segments. The most common places for custom segments are the App layer and the Shared layer, where slices don't make sense. Make sure that the name of these segments describes the purpose of the content, not its essence. For example, `components`, `hooks`, and `types` are bad segment names because they aren't that helpful when you're looking for code. --- ### Explicit business logic Easily discoverable architecture thanks to domain scopes ---