Back to Blog

    Engineering

    Spec-driven development in VS Code: our SPFx template

    How we write specs for coding agents in VS Code: a three-step workflow and a complete template for a SharePoint web part built with SPFx.

    February 27, 20267 min read
    Christof Schnyder

    Christof Schnyder

    Software Architect, Co-Founder

    christof.schnyder@cnext.ch
    CNEXT AI Agent
    In this article

    A coding agent builds a SharePoint web part correctly when the specification leaves nothing open: compatible versions, reasoned architecture decisions, prioritised requirements, interfaces, error messages, tests and deployment. At CNEXT we work in VS Code with coding agents, so for us the spec comes before the code. Below you will find our workflow and the complete spec for a weather web part, ready to use as a template.

    Our three-step workflow

    1. 1Set the context: a central context file in the repository records architecture decisions, tech stack and coding guidelines, for example a replit.md or .cursorrules, depending on the tool.
    2. 2Specify the task: before a single line of code is written, we describe the ‘what’ and the ‘why’, including acceptance criteria.
    3. 3Prototype iteratively: the agent builds; we review the spec, not just the code.

    Coding agents in VS Code such as GitHub Copilot read the project structure, work directly in the file system and can run commands in the terminal. That makes clear guardrails all the more important. There is a side benefit: the architecture decisions exist as text, so new team members read them just as the agent does. Our principle: Design for less complexity, design for less overhead.

    What a spec for agents needs

    CriterionMeaning
    ExplicitNo assumptions. State exactly which libraries and versions apply.
    ModularBreak large tasks into small steps the agent can implement one at a time.
    TestableDefine acceptance criteria against which the code and tests are checked.

    For SPFx, ‘explicit’ above all means that SPFx, Node, TypeScript and React come from the same row of Microsoft's SPFx compatibility table. The table pairs SPFx 1.19 with React 17.0.1; the template below uses that combination.

    The template: a weather web part for SharePoint

    With this spec, an agent in VS Code builds a complete SPFx web part, including architecture decisions, service layer, error handling, caching and deployment. Adopt its structure and level of detail; adapt the versions and the weather provider to your project.

    1. Context and tech stack

    • Framework: SPFx 1.19 (SharePoint Framework)
    • Libraries: React 17.0.1, Fluent UI v9, CSS Modules
    • API: OpenWeatherMap (Current Weather and 5-Day Forecast), queried through a dedicated server-side service
    • Target: SharePoint Online and Microsoft Teams (personal tab and full width)
    • Auth: app registration with the user.read scope for location-based personalisation
    • API key: stored only in the server-side service; the browser receives only the values it needs
    • Caching: localStorage with TTL (15 minutes for current data, 60 minutes for the forecast)
    • Monitoring: Application Insights telemetry via @microsoft/applicationinsights-web

    2. Architecture decision records (ADR)

    ADRDecisionRationale
    ADR-001Fluent UI v9 instead of Tailwind CSSSharePoint-native look, theming compatibility, built-in accessibility
    ADR-002SPFx HttpClient instead of fetchRuns in the web part's SPFx context. It does not handle CORS rules or retries automatically; the spec defines both and the tests check them.
    ADR-003localStorage cache with TTLShows the last data during an outage, reduces calls to the weather service, needs no server state. The TTL values are design decisions.
    ADR-004Service interface patternDependency injection for unit tests, mock service for development
    ADR-005Error boundary per widgetA single error does not bring down the whole web part
    ADR-006API key only in the server-side serviceThe key belongs neither in the property pane nor in the shipped JavaScript

    3. Functional requirements

    Must have (P0):

    • Current weather for a configurable location (city or coordinates), showing place, temperature and observation time
    • 5-day forecast in 3-hour intervals as horizontally scrolling cards
    • Property pane: location (text with autocomplete), unit (toggle Celsius/Fahrenheit), showForecast (toggle), refreshInterval (dropdown: 15/30/60 minutes)
    • Error handling with clear messages and a retry button
    • Responsive layout: full width plus 1/2 and 1/3 columns
    • Accessibility: WCAG 2.1 AA, keyboard navigation, screen reader support

    Should have (P1):

    • Location detection via the browser Geolocation API, with an IP-based fallback
    • Weather warnings via the OpenWeatherMap One Call API
    • Background colour adapts to the weather (sunny = warm, rain = cool)
    • Dark mode via SharePoint theme detection

    Nice to have (P2):

    • Mini widget mode for narrow columns (icon and temperature only)
    • Multilingual support via the SharePoint language pack (this.context.pageContext.cultureInfo)

    4. Technical specification

    Service layer:

    interface IWeatherService {
      getCurrentWeather(location: string, unit: Unit): Promise<WeatherData>;
      getForecast(location: string, unit: Unit): Promise<ForecastData>;
      searchLocations(query: string): Promise<LocationResult[]>;
      getAlerts(lat: number, lon: number): Promise<WeatherAlert[]>;
    }
    
    interface WeatherData {
      temp: number;
      feelsLike: number;
      humidity: number;
      windSpeed: number;
      windDirection: number;
      condition: WeatherCondition;
      icon: string;
      sunrise: Date;
      sunset: Date;
      location: { city: string; country: string; lat: number; lon: number };
      lastUpdated: Date;
    }
    
    type WeatherCondition =
      | "clear" | "clouds" | "rain" | "drizzle"
      | "thunderstorm" | "snow" | "mist" | "fog";

    Caching:

    class WeatherCache {
      private readonly CURRENT_TTL = 15 * 60 * 1000;   // 15 minutes
      private readonly FORECAST_TTL = 60 * 60 * 1000;   // 60 minutes
    
      get(key: string): CachedData | null {
        const raw = localStorage.getItem('spfx-weather-' + key);
        if (!raw) return null;
        const parsed = JSON.parse(raw);
        if (Date.now() - parsed.timestamp > parsed.ttl) {
          localStorage.removeItem('spfx-weather-' + key);
          return null;
        }
        return parsed.data;
      }
    }

    Error handling:

    • HTTP 401 (key in the server-side service invalid): ‘The weather service is unavailable. Please contact your IT team.’
    • HTTP 404: ‘Location not found. Try a different city.’
    • HTTP 429: ‘API limit reached. Next update in [countdown].’
    • Network error: the last cached data with the note ‘Offline — data from [timestamp]’
    • Timeout (over 5 seconds): cancel; with a cache entry, show the last data and its timestamp, otherwise a retry button

    5. Implementation

    Components:

    WeatherWebPart (SPFx Entry)
    ├── WeatherProvider (Context + Service Injection)
    │   ├── ErrorBoundary
    │   │   ├── CurrentWeather (main display)
    │   │   │   ├── WeatherIcon (animated SVG icons)
    │   │   │   ├── TemperatureDisplay
    │   │   │   └── WeatherDetails (Wind, Humidity, etc.)
    │   │   ├── ForecastStrip (horizontal scroll cards)
    │   │   │   └── ForecastCard (3-hour interval)
    │   │   └── AlertBanner (weather warnings)
    │   └── LoadingState / ErrorState / EmptyState
    └── PropertyPane (configuration)

    Hooks:

    • useWeather(location, unit): main hook with loading, error and data state, auto-refresh via setInterval, cache integration
    • useGeolocation(): browser geolocation with permission handling
    • useThemeDetection(): SharePoint theme for adaptive colours
    • useResponsiveLayout(): detects the web part width for mini, standard and full mode

    6. Tests

    Test typeToolCoverage
    Unit testsJest + React Testing LibraryService layer, cache, hooks (>80%)
    IntegrationSPFx WorkbenchProperty pane, rendering, theme
    E2EPlaywrightLive test in SharePoint Online
    Mock serviceMockWeatherServiceOffline development, all weather states

    Acceptance cases: valid and invalid place names, empty responses, timeout, keyboard use, theme change and mobile view.

    7. Deployment

    Build and package:

    gulp bundle --ship
    gulp package-solution --ship

    Deploy with PnP PowerShell:

    Connect-PnPOnline -Url "https://tenant.sharepoint.com/sites/appcatalog"
    Add-PnPApp -Path "./sharepoint/solution/weather-webpart.sppkg" -Overwrite

    Limits

    • The spec is a working basis, not a security certificate. Review the generated code in the diff, run the tests and deploy to a test tenant first.
    • Versions only work as a set. If you choose a newer row of the compatibility table, adjust the dependencies and build commands as well; the commands above belong to SPFx 1.19.
    • This template does not describe the server-side service that holds the API key. That service needs its own spec.

    Source

    Agentic EngineeringAgentic AISchweiz
    Teilen:

    AI tools may have supported the creation of this article. CNEXT is responsible for the published content. Product features and prices can change; check the linked primary sources for current details.

    Christof Schnyder

    Christof Schnyder

    Software Architect, Co-Founder

    Discuss an SPFx prototype

    We show your team how to bring VS Code and coding agents into your way of working with clear specs.