Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add storefront setup instructions to getting started (#14287)
Damian Legawiec87ab70565343
diff --git a/CLAUDE.md b/CLAUDE.mdindex 128d6c822d..13858cd2d8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -85,6 +85,7 @@ Day-to-day from the repo root: `pnpm server:dev` (foreground — streams web + w| What changed | What to run ||---|---|| Ruby code in `spree/*` gems | Nothing — bind-mounted, reloads on next request |+| Tailwind classes in `spree/admin` templates/helpers/JS | Nothing — a watcher in the web container rebuilds the admin CSS within ~15s. If changes still don't reach the browser, delete `server/public/assets/.manifest.json` (stale precompile output that freezes asset serving) and restart web — `pnpm server:dev` boots handle this automatically. || New migration in a gem | Nothing — the next `pnpm server:dev` boot runs `spree:install:migrations db:prepare` (or `cd server && pnpm exec spree migrate` while running) || Gem dependencies (gemspec / Gemfile / starter `Gemfile.lock` drift after a pull) | Nothing — the next `pnpm server:dev` boot self-heals (`bundle check || bundle install` into the `bundle_cache` volume); while running: `cd server && pnpm exec spree bundle install` || Compose files / `server/.env` | `pnpm server:dev` (force-recreates web + worker) |diff --git a/docs/developer/admin/custom-javascript.mdx b/docs/developer/admin/custom-javascript.mdxindex f3062c914a..c089d97159 100644--- a/docs/developer/admin/custom-javascript.mdx+++ b/docs/developer/admin/custom-javascript.mdx@@ -109,9 +109,9 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an</Tab></Tabs>-2. Creating a new file in the `app/views/spree/admin/shared/my_tracking_code.html.erb`, where you can add your tracking code, eg.+2. Creating a new partial file `app/views/spree/admin/shared/_my_tracking_code.html.erb` (note the leading underscore — it's rendered as a partial), where you can add your tracking code, eg.- ```erb+ ```erb app/views/spree/admin/shared/_my_tracking_code.html.erb<script>console.log("I'm a spy!");</script>diff --git a/docs/developer/storefront/rails/custom-javascript.mdx b/docs/developer/storefront/rails/custom-javascript.mdxindex 0b8faff138..7826f227c1 100644--- a/docs/developer/storefront/rails/custom-javascript.mdx+++ b/docs/developer/storefront/rails/custom-javascript.mdx@@ -109,9 +109,9 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an</Tab></Tabs>-2. Creating a new file in the `app/views/spree/shared/my_tracking_code.html.erb`, where you can add your tracking code, eg.+2. Creating a new partial file `app/views/spree/shared/_my_tracking_code.html.erb` (note the leading underscore — it's rendered as a partial), where you can add your tracking code, eg.- ```erb app/views/spree/shared/my_tracking_code.html.erb+ ```erb app/views/spree/shared/_my_tracking_code.html.erb<script>console.log("I'm a spy!");</script>diff --git a/scripts/docker-compose.edge.yml b/scripts/docker-compose.edge.ymlindex abae42b420..be31aa152b 100644--- a/scripts/docker-compose.edge.yml+++ b/scripts/docker-compose.edge.yml@@ -38,10 +38,23 @@ services:# or 500 on ActiveRecord::PendingMigrationError after every such pull.# `bundle check` is sub-second when clean; the rails invocation is one# boot (~5s) that no-ops when nothing changed.+ #+ # The backgrounded tailwindcss:watch recompiles the admin CSS when+ # templates in the mounted monorepo gems change (it polls mtimes — FS+ # events don't cross the bind mount). `spree dev` starts the same watcher+ # via a detached exec, but this compose flow never goes through the CLI,+ # so the watcher must ride the web container's boot command. The one-shot+ # build stays in the foreground chain so a broken build still fails the+ # boot loudly instead of only warning in the watcher's log.+ # rm -f of the propshaft manifest: if public/assets/.manifest.json exists+ # (left behind by any assets:precompile — image builds, test prep, a+ # one-off rake run), Propshaft silently switches to its static resolver+ # and serves that frozen snapshot instead of app/assets/builds, so admin+ # CSS rebuilds never reach the browser. Dev must always resolve live.command:["sh", "-c",- "(bundle check || bundle install) && bin/rails spree:install:migrations db:prepare && bin/rails spree:admin:tailwindcss:build && exec bin/rails server -b 0.0.0.0 -p 3000"+ "(bundle check || bundle install) && rm -f public/assets/.manifest.json && bin/rails spree:install:migrations db:prepare && bin/rails spree:admin:tailwindcss:build && (bin/rails spree:admin:tailwindcss:watch &) && exec bin/rails server -b 0.0.0.0 -p 3000"]worker:diff --git a/spree/admin/app/assets/images/vercel-deploy-button.svg b/spree/admin/app/assets/images/vercel-deploy-button.svgnew file mode 100644index 0000000000..5eaebe3abe--- /dev/null+++ b/spree/admin/app/assets/images/vercel-deploy-button.svg@@ -0,0 +1,14 @@+<svg xmlns="http://www.w3.org/2000/svg" width="103" height="32" fill="none">+ <rect width="103" height="32" fill="#1A1A1A" rx="6"/>+ <rect width="102" height="31" x=".5" y=".5" stroke="#fff" stroke-opacity=".14" rx="5.5" />+ <g clip-path="url(#a)">+ <path fill="#EDEDED" fill-rule="evenodd" d="m16 10.75 6 10.5H10l6-10.5Z" clip-rule="evenodd" />+ </g>+ <path stroke="#fff" stroke-opacity=".14" d="M31.5 1v30" />+ <path fill="#EDEDED" d="M47.4 11.06c3.1 0 4.85 1.8 4.85 4.98 0 3.18-1.7 4.96-4.77 4.96h-3.26v-9.94h3.18Zm-1.7 8.57h1.7c2.22 0 3.31-1.18 3.31-3.59 0-2.43-1.09-3.6-3.31-3.6h-1.7v7.19Zm7.83-2.34c0-2.37 1.38-3.88 3.51-3.88 1.74 0 3.25 1.15 3.33 3.8l.02.5h-5.34c.12 1.39.82 2.2 2 2.2.73 0 1.4-.42 1.7-1.14l1.53.12a3.3 3.3 0 0 1-3.24 2.28c-2.13 0-3.51-1.51-3.51-3.88Zm1.55-.7h3.77c-.2-1.43-.97-1.92-1.8-1.92-1.1 0-1.79.72-1.97 1.92Zm6.98 6.51v-9.52h1.36l.04 1.08c.4-.8 1.17-1.25 2.25-1.25 2.19 0 3.2 1.8 3.2 3.88 0 2.07-1.01 3.88-3.2 3.88-1.02 0-1.78-.4-2.2-1.18v3.11h-1.45Zm1.31-5.81c0 1.33.6 2.6 2 2.6 1.42 0 2-1.26 2-2.6 0-1.33-.58-2.6-2-2.6-1.4 0-2 1.27-2 2.6Zm7.36-6.23h1.45v8.25c0 .33.16.49.48.49h.62V21h-.93c-.98 0-1.62-.63-1.62-1.62v-8.32Zm7.1 10.1c-2.13 0-3.52-1.5-3.52-3.87s1.39-3.88 3.51-3.88c2.13 0 3.52 1.51 3.52 3.88s-1.39 3.88-3.52 3.88Zm-2-3.87c0 1.62.72 2.6 2 2.6 1.27 0 2-.98 2-2.6s-.73-2.6-2-2.6c-1.28 0-2 .98-2 2.6Zm6.07-3.71h1.49l2.11 5.88 2.05-5.88h1.47l-2.97 8.29c-.31.85-.87 1.23-1.78 1.23h-1v-1.19h.8c.38 0 .6-.14.73-.49l.25-.63h-.46l-2.69-7.21Z"/>+ <defs>+ <clipPath id="a">+ <path fill="#fff" d="M0 0h12v12H0z" fill-opacity="1" transform="translate(10 10)"/>+ </clipPath>+ </defs>+</svg>diff --git a/spree/admin/app/controllers/spree/admin/storefront_controller.rb b/spree/admin/app/controllers/spree/admin/storefront_controller.rbnew file mode 100644index 0000000000..e3a6e0ef40--- /dev/null+++ b/spree/admin/app/controllers/spree/admin/storefront_controller.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++module Spree+ module Admin+ class StorefrontController < BaseController+ include Spree::Admin::SettingsConcern++ # GET /admin/storefront+ def show+ @breadcrumb_icon = 'building-store'+ add_breadcrumb Spree.t('admin.storefront_setup.title'), spree.admin_storefront_path++ @publishable_key = find_or_create_publishable_key+ @deployment_origin = normalize_origin(params[:'deployment-url'])+ @deployment_origin_allowed = @deployment_origin.present? && current_store.allowed_origin?(@deployment_origin)+ @vercel_dashboard_url = vercel_dashboard_url+ @storefront_origins = current_store.allowed_origins.order(:created_at).reject(&:loopback?)+ end++ # PATCH /admin/storefront+ #+ # Saves the storefront URL preference (used as the base for links in+ # customer emails and as the "connected" signal for non-web storefronts),+ # optionally adding it as an allowed origin for browser-based storefronts.+ def update+ origin = normalize_origin(params[:storefront_url])++ if origin.nil?+ flash[:error] = Spree.t('admin.storefront_setup.invalid_origin')+ elsif current_store.update(preferred_storefront_url: origin)+ current_store.allowed_origins.find_or_create_by(origin: origin) if params[:add_allowed_origin] == '1'+ flash[:success] = Spree.t('admin.storefront_setup.storefront_url_saved', url: origin)+ else+ flash[:error] = current_store.errors.full_messages.to_sentence+ end++ redirect_to spree.admin_storefront_path, status: :see_other+ end++ # POST /admin/storefront/allow_origin+ def allow_origin+ origin = normalize_origin(params[:origin])++ if origin.nil?+ flash[:error] = Spree.t('admin.storefront_setup.invalid_origin')+ else+ allowed_origin = current_store.allowed_origins.find_or_initialize_by(origin: origin)++ if allowed_origin.persisted? || allowed_origin.save+ current_store.update(preferred_storefront_url: origin) if current_store.preferred_storefront_url.blank?+ flash[:success] = Spree.t('admin.storefront_setup.origin_allowed', origin: origin)+ else+ flash[:error] = allowed_origin.errors.full_messages.to_sentence+ end+ end++ redirect_to spree.admin_storefront_path, status: :see_other+ end++ private++ # Every action here is store configuration (publishable keys, allowed+ # origins, store preferences), so gate the whole page behind store+ # management — granted by e.g. Spree::PermissionSets::ConfigurationManagement.+ def authorize_admin+ authorize! :admin, Spree::Store+ authorize! :update, current_store+ end++ # The storefront needs a publishable key; reuse the oldest active one+ # (usually the seeded "Default") and mint one for stores that have none.+ def find_or_create_publishable_key+ current_store.api_keys.active.publishable.order(:created_at).first ||+ current_store.api_keys.create!(+ name: 'Storefront',+ key_type: 'publishable',+ created_by: try_spree_current_user+ )+ end++ # Normalizes user or Vercel-callback input (possibly a bare host like+ # my-shop.vercel.app) to a canonical origin string (scheme://host[:port]),+ # or nil when it's not a valid http(s) URL.+ def normalize_origin(raw)+ raw = raw.to_s.strip+ return if raw.blank?++ candidate = raw.match?(%r{\Ahttps?://}i) ? raw : "https://#{raw}"+ parsed = Spree::AllowedOrigin.parse_origin(candidate)+ return if parsed.nil?++ origin = "#{parsed[:scheme]}://#{parsed[:host]}"+ origin += ":#{parsed[:port]}" unless [80, 443].include?(parsed[:port])+ origin+ end++ # Only link back to the Vercel dashboard when the callback param actually+ # points at vercel.com — never reflect an arbitrary URL as a link.+ def vercel_dashboard_url+ url = params[:'project-dashboard-url'].to_s+ parsed = Spree::AllowedOrigin.parse_origin(url)+ return unless parsed && parsed[:scheme] == 'https'++ url if parsed[:host] == 'vercel.com' || parsed[:host].end_with?('.vercel.com')+ end+ end+ end+enddiff --git a/spree/admin/app/helpers/spree/admin/onboarding_helper.rb b/spree/admin/app/helpers/spree/admin/onboarding_helper.rbindex ae4d613df6..2caaec3d13 100644--- a/spree/admin/app/helpers/spree/admin/onboarding_helper.rb+++ b/spree/admin/app/helpers/spree/admin/onboarding_helper.rb@@ -10,7 +10,7 @@ module Spreeif condition == trueicon('check', class: 'rounded-full inline-flex items-center bg-green-200 text-green-600 border-green-200 p-1')else- icon('check', class: 'rounded-full inline-flex items-center border-dashed text-gray-300 p-1')+ icon('circle-dashed-check', class: 'rounded-full inline-flex items-center border-dashed text-gray-300 p-1')end.html_safeendenddiff --git a/spree/admin/app/helpers/spree/admin/storefront_helper.rb b/spree/admin/app/helpers/spree/admin/storefront_helper.rbnew file mode 100644index 0000000000..7f50eda9ae--- /dev/null+++ b/spree/admin/app/helpers/spree/admin/storefront_helper.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module Spree+ module Admin+ module StorefrontHelper+ STOREFRONT_REPOSITORY_URL = 'https://github.com/spree/storefront'++ # Builds the Vercel deploy-button URL for the storefront starter, prefilled+ # with the store's API URL and publishable key (both non-secret), and+ # redirecting back to the admin storefront page after a successful deploy+ # so the deployed domain can be added as an allowed origin.+ #+ # @param store [Spree::Store]+ # @param api_key [Spree::ApiKey] an active publishable key+ # @return [String]+ def vercel_deploy_url(store, api_key)+ query = {+ 'repository-url' => STOREFRONT_REPOSITORY_URL,+ 'project-name' => "#{store.code}-storefront",+ 'repository-name' => "#{store.code}-storefront",+ 'env' => 'SPREE_API_URL,SPREE_PUBLISHABLE_KEY',+ 'envDefaults' => {+ 'SPREE_API_URL' => store.formatted_url,+ 'SPREE_PUBLISHABLE_KEY' => api_key.token+ }.to_json,+ 'envDescription' => Spree.t('admin.storefront_setup.env_description'),+ 'envLink' => "#{STOREFRONT_REPOSITORY_URL}#readme",+ 'redirect-url' => spree.admin_storefront_url+ }++ "https://vercel.com/new/clone?#{query.to_query}"+ end++ # True when the store's public URL points at a loopback host, which+ # Vercel's build servers cannot reach.+ #+ # @param store [Spree::Store]+ # @return [Boolean]+ def store_url_loopback?(store = current_store)+ Spree::AllowedOrigin::LOOPBACK_HOSTS.include?(+ Spree::AllowedOrigin.parse_origin(store.formatted_url)&.dig(:host)+ )+ end+ end+ end+enddiff --git a/spree/admin/app/views/spree/admin/dashboard/setup_tasks/_setup_storefront.html.erb b/spree/admin/app/views/spree/admin/dashboard/setup_tasks/_setup_storefront.html.erbnew file mode 100644index 0000000000..f2203c16ec--- /dev/null+++ b/spree/admin/app/views/spree/admin/dashboard/setup_tasks/_setup_storefront.html.erb@@ -0,0 +1,18 @@+<% if done %>+ <p>+ <%= Spree.t('admin.store_setup_tasks.storefront.done') %>+ <%= link_to current_store.storefront_url, current_store.storefront_url, target: :_blank, rel: 'noopener', class: 'font-medium' %>+ </p>+ <% if can?(:update, current_store) %>+ <div>+ <%= link_to Spree.t('admin.store_setup_tasks.storefront.manage'), spree.admin_storefront_path, class: 'btn btn-light', data: { turbo_frame: '_top' } %>+ </div>+ <% end %>+<% else %>+ <p><%= Spree.t('admin.store_setup_tasks.storefront.copy') %></p>+ <% if can?(:update, current_store) %>+ <div>+ <%= link_to Spree.t('admin.store_setup_tasks.storefront.setup'), spree.admin_storefront_path, class: 'btn btn-primary', data: { turbo_frame: '_top' } %>+ </div>+ <% end %>+<% end %>diff --git a/spree/admin/app/views/spree/admin/storefront/show.html.erb b/spree/admin/app/views/spree/admin/storefront/show.html.erbnew file mode 100644index 0000000000..fdb8d446ee--- /dev/null+++ b/spree/admin/app/views/spree/admin/storefront/show.html.erb@@ -0,0 +1,155 @@+<div class="grid grid-cols-12 gap-6 pt-6">+ <div class="col-span-12 lg:col-span-8 lg:col-start-3 mb-6">+ <h2 class="page-header-title">+ <%= onboarding_check_circle(current_store.storefront_setup?) %>+ <%= Spree.t('admin.storefront_setup.title') %>+ </h2>+ <p class="mb-4">+ <%= Spree.t('admin.storefront_setup.description') %>+ </p>++ <% if @deployment_origin.present? %>+ <div class="card mb-6">+ <div class="card-body flex flex-col gap-3">+ <% if @deployment_origin_allowed %>+ <div class="flex items-center gap-2">+ <%= onboarding_check_circle(true) %>+ <span>+ <%= Spree.t('admin.storefront_setup.deployment_already_allowed') %>+ <%= link_to @deployment_origin, @deployment_origin, target: :_blank, rel: 'noopener', class: 'font-medium' %>+ </span>+ </div>+ <% else %>+ <h5 class="font-medium">+ 🎉 <%= Spree.t('admin.storefront_setup.deployed_title') %>+ </h5>+ <p>+ <%= Spree.t('admin.storefront_setup.deployed_copy') %>+ <%= link_to @deployment_origin, @deployment_origin, target: :_blank, rel: 'noopener', class: 'font-medium' %>+ </p>+ <div class="flex items-center gap-2">+ <%= form_with url: spree.admin_storefront_allow_origin_path, method: :post, data: { turbo: false } do %>+ <%= hidden_field_tag :origin, @deployment_origin %>+ <button type="submit" class="btn btn-primary">+ <%= Spree.t('admin.storefront_setup.allow_origin_button') %>+ </button>+ <% end %>+ <% if @vercel_dashboard_url.present? %>+ <%= link_to @vercel_dashboard_url, target: :_blank, rel: 'noopener', class: 'btn btn-light' do %>+ <%= icon('external-link') %>+ <%= Spree.t('admin.storefront_setup.view_on_vercel') %>+ <% end %>+ <% end %>+ </div>+ <% end %>+ </div>+ </div>+ <% end %>++ <% if current_store.storefront_setup? %>+ <div class="alert alert-success mb-6">+ <%= Spree.t('admin.storefront_setup.done') %>+ <%= link_to current_store.storefront_url, current_store.storefront_url, target: :_blank, rel: 'noopener', class: 'font-medium' %>+ </div>+ <% end %>++ <div class="card mb-6">+ <div class="card-header flex justify-between">+ <h5 class="card-title"><%= Spree.t('admin.storefront_setup.deploy_title') %></h5>++ <%= external_link_to Spree.t('admin.storefront_setup.see_online_demo'), 'https://demo.spreecommerce.org' %>+ </div>+ <div class="card-body">+ <p class="mb-3"><%= Spree.t('admin.storefront_setup.deploy_copy') %></p>+ <div class="mb-2">+ <% if store_url_loopback?(current_store) %>+ <div class="cursor-not-allowed flex gap-2 items-center">+ <%= image_tag 'vercel-deploy-button.svg', alt: Spree.t('admin.storefront_setup.deploy_button'), height: 32, class: 'disabled opacity-25' %>+ <span data-controller="tooltip">+ <%= icon('alert-circle', class: 'text-yellow-500') %>+ <%= tooltip(Spree.t('admin.storefront_setup.loopback_warning')) %>+ </span>+ </div>+ <% else %>+ <%= link_to vercel_deploy_url(current_store, @publishable_key) do %>+ <%= image_tag 'vercel-deploy-button.svg', alt: Spree.t('admin.storefront_setup.deploy_button'), height: 32 %>+ <% end %>+ <% end %>+ </div>+ <%= external_link_to Spree.t('admin.storefront_setup.local_installation_instructions'), 'https://spreecommerce.org/docs/developer/storefront/nextjs/quickstart' %>+ </div>+ </div>++ <div class="card mb-6">+ <div class="card-header">+ <h5 class="card-title"><%= Spree.t('admin.storefront_setup.connect_title') %></h5>+ </div>+ <div class="card-body flex flex-col gap-3">+ <p><%= Spree.t('admin.storefront_setup.connect_copy') %></p>++ <div class="form-group mb-0">+ <label><%= Spree.t('admin.storefront_setup.api_url_label') %></label>+ <div class="input-group gap-0 pr-1">+ <input type="text" class="grow text-truncate" spellcheck="false" value="<%= current_store.formatted_url %>" readonly>+ <%= clipboard_component(current_store.formatted_url,+ button_class: 'btn hover:bg-gray-100 p-1 rounded',+ icon_class: 'mr-0') %>+ </div>+ </div>++ <div class="form-group mb-0">+ <label><%= Spree.t('admin.storefront_setup.publishable_key_label') %></label>+ <div data-controller="password-visibility" class="input-group gap-0 pr-1">+ <input type="password" class="grow text-truncate" data-password-visibility-target="input" spellcheck="false" value="<%= @publishable_key.token %>" readonly>++ <button type="button" class="btn hover:bg-gray-100 p-1 mr-1 rounded" data-action="password-visibility#toggle">+ <span data-password-visibility-target="icon"><%= icon 'eye', class: 'mr-0' %></span>+ <span data-password-visibility-target="icon" class="hidden"><%= icon 'eye-off', class: 'mr-0' %></span>+ </button>++ <%= clipboard_component(@publishable_key.token,+ button_class: 'btn hover:bg-gray-100 p-1 rounded',+ icon_class: 'mr-0') %>+ </div>+ </div>++ <%= form_with url: spree.admin_storefront_path, method: :patch, data: { turbo: false }, class: 'flex flex-col gap-3 mt-2' do %>+ <div class="form-group mb-0">+ <label for="storefront_url"><%= Spree.t('admin.storefront_setup.storefront_url_label') %></label>+ <input type="text" name="storefront_url" id="storefront_url" class="form-input" spellcheck="false"+ placeholder="https://myshop.com" value="<%= current_store.preferred_storefront_url %>">+ <p class="text-gray-500 text-sm mt-1 mb-0"><%= Spree.t('admin.storefront_setup.storefront_url_help') %></p>+ </div>+ <div class="form-checkbox">+ <%= check_box_tag :add_allowed_origin, '1', true, class: 'custom-control-input' %>+ <label class="custom-control-label" for="add_allowed_origin">+ <%= Spree.t('admin.storefront_setup.add_allowed_origin_label') %>+ </label>+ </div>+ <div>+ <button type="submit" class="btn btn-primary"><%= Spree.t('actions.save') %></button>+ </div>+ <% end %>+ </div>+ </div>++ <% if @storefront_origins.any? %>+ <div class="card mb-6">+ <div class="card-header">+ <h5 class="card-title"><%= Spree.t('admin.storefront_setup.connected_title') %></h5>+ </div>+ <div class="card-body flex flex-col gap-2">+ <% @storefront_origins.each do |allowed_origin| %>+ <div class="flex items-center gap-2">+ <%= icon('world', class: 'text-gray-500') %>+ <%= link_to allowed_origin.origin, allowed_origin.origin, target: :_blank, rel: 'noopener' %>+ </div>+ <% end %>+ <p class="text-gray-500 text-sm mb-0 mt-2">+ <%= link_to Spree.t('admin.storefront_setup.manage_allowed_origins'), spree.admin_allowed_origins_path %>+ </p>+ </div>+ </div>+ <% end %>+ </div>+</div>diff --git a/spree/admin/config/initializers/spree_admin_navigation.rb b/spree/admin/config/initializers/spree_admin_navigation.rbindex 4b6a1ad8cf..bbfe97648c 100644--- a/spree/admin/config/initializers/spree_admin_navigation.rb+++ b/spree/admin/config/initializers/spree_admin_navigation.rb@@ -251,6 +251,15 @@ Rails.application.config.after_initialize doactive: -> { controller_name == 'policies' },if: -> { can?(:manage, Spree::Policy) }+ # Storefront setup+ settings_nav.add :storefront,+ label: 'admin.storefront',+ url: :admin_storefront_path,+ icon: 'building-store',+ position: 60,+ active: -> { controller_name == 'storefront' },+ if: -> { can?(:update, current_store) }+# Channelssettings_nav.add :channels,label: :channels,diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.ymlindex 0823f9f53d..1e5309d969 100644--- a/spree/admin/config/locales/en.yml+++ b/spree/admin/config/locales/en.yml@@ -534,12 +534,47 @@ en:setup: Setup Payment Methodstitle: Please setup Payment Methods for your storeset_customer_support_email: Set customer support email+ setup_payment_method: Setup Payment Methods+ setup_storefront: Setup Storefrontsetup_taxes_collection: Setup taxes collection+ storefront:+ copy: Spree is headless — connect any storefront to the Store API, whether it's a web storefront or a mobile app. Need one? Deploy the official Next.js storefront in one click.+ done: Your storefront is connected and live at+ manage: Manage storefront+ setup: Setup Storefronttaxes:copy: In order to collect taxes, please setup your tax rates.done: You're all set! You can always manage your taxes on the <a href="%{link}" data-turbo-frame="_top">settings</a> page.setup: Setup Tax Ratesstorefront: Storefront+ storefront_setup:+ add_allowed_origin_label: Also add this URL as an allowed origin — required for browser-based storefronts to call the Store API+ allow_origin_button: Allow this origin & finish setup+ api_url_label: Store API URL+ connect_copy: 'Use these credentials in any client that talks to the Store API — a web storefront, a mobile app, or anything else:'+ connect_title: Connect your storefront+ connected_title: Connected storefronts+ deploy_button: Deploy to Vercel+ deploy_copy: Don't have a storefront yet? The fastest way to launch is the official open-source Next.js storefront. Deploying clones it to your Git account and builds it on Vercel with your credentials prefilled — once it finishes, you'll be redirected back here to complete the setup.+ deploy_title: 'Recommended: deploy the official Next.js storefront'+ deployed_copy: It's now live at+ deployed_title: Your storefront has been deployed!+ deployment_already_allowed: This storefront origin is already allowed —+ description: Connect your web storefront or mobile app with the credentials below, or deploy the official Next.js storefront in one click.+ done: Your storefront is connected and live at+ env_description: Your Spree Store API URL and publishable key. Both are prefilled from your store — adjust them before deploying if needed.+ invalid_origin: This doesn't look like a valid storefront URL.+ local_installation_instructions: Local installation instructions+ loopback_warning: Your store URL points to a local address that Vercel's build servers can't reach. Deploy your backend to a public URL first, or adjust the SPREE_API_URL value during the Vercel setup.+ manage_allowed_origins: Manage allowed origins+ origin_allowed: "%{origin} can now access your Store API."+ publishable_key_label: Publishable API key+ see_online_demo: See online demo+ storefront_url_help: The URL customers use to reach your storefront. It becomes the base for links in customer emails — mobile-only setups can point it at their landing page.+ storefront_url_label: Storefront URL+ storefront_url_saved: 'Storefront URL saved: %{url}'+ title: Setup Storefront+ view_on_vercel: View on Vercelsuccessful: Successfulsuccessfully_reset_digital_links_limit: Download limits have been resettable:diff --git a/spree/admin/config/routes.rb b/spree/admin/config/routes.rbindex fe916ea3a7..8b1c3c2339 100644--- a/spree/admin/config/routes.rb+++ b/spree/admin/config/routes.rb@@ -280,6 +280,11 @@ Spree::Core::Engine.add_routes doendresources :allowed_origins, except: :show+ # storefront setup+ get '/storefront', to: 'storefront#show', as: :storefront+ patch '/storefront', to: 'storefront#update'+ post '/storefront/allow_origin', to: 'storefront#allow_origin', as: :storefront_allow_origin+# errorsget '/forbidden', to: 'errors#show', code: 403, as: :forbiddenif Rails.env.test?diff --git a/spree/admin/spec/controllers/spree/admin/dashboard_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/dashboard_controller_spec.rbindex 1dda9fc288..101b4796c7 100644--- a/spree/admin/spec/controllers/spree/admin/dashboard_controller_spec.rb+++ b/spree/admin/spec/controllers/spree/admin/dashboard_controller_spec.rb@@ -45,6 +45,11 @@ describe Spree::Admin::DashboardController, type: :controller doget :getting_startedexpect(response).to render_template(:getting_started)end++ it 'renders the storefront setup task' do+ get :getting_started+ expect(response.body).to include('Setup Storefront')+ endenddescribe '#dismiss_enterprise_edition_notice' dodiff --git a/spree/admin/spec/controllers/spree/admin/storefront_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/storefront_controller_spec.rbnew file mode 100644index 0000000000..92fd54f1db--- /dev/null+++ b/spree/admin/spec/controllers/spree/admin/storefront_controller_spec.rb@@ -0,0 +1,195 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Admin::StorefrontController, type: :controller do+ stub_authorization!+ render_views++ let(:store) { @default_store }++ describe 'authorization' do+ context 'without store management permission' do+ before do+ allow_any_instance_of(described_class).to receive(:current_ability).and_return(Spree::Ability.new(nil))+ end++ it 'denies access' do+ get :show++ expect(response).to redirect_to(spree.admin_forbidden_path)+ end+ end+ end++ describe 'GET #show' do+ subject(:show) { get :show, params: params }++ let(:params) { {} }++ context 'with an active publishable key' do+ let!(:api_key) { create(:api_key, store: store) }++ it 'renders and reuses the existing key' do+ expect { show }.not_to change(Spree::ApiKey, :count)++ expect(response).to render_template(:show)+ expect(assigns[:publishable_key]).to eq(api_key)+ end+ end++ context 'without a publishable key' do+ it 'creates one for the storefront' do+ expect { show }.to change { store.api_keys.active.publishable.count }.from(0).to(1)++ expect(assigns[:publishable_key].name).to eq('Storefront')+ end++ it 'does not reuse a revoked key' do+ revoked = create(:api_key, :revoked, store: store)++ show++ expect(assigns[:publishable_key]).not_to eq(revoked)+ end+ end++ context 'with Vercel callback params' do+ let(:params) do+ {+ 'deployment-url' => 'my-shop.vercel.app',+ 'project-dashboard-url' => 'https://vercel.com/acme/my-shop'+ }+ end++ it 'normalizes the deployment origin and renders the confirmation' do+ show++ expect(assigns[:deployment_origin]).to eq('https://my-shop.vercel.app')+ expect(assigns[:deployment_origin_allowed]).to be false+ expect(assigns[:vercel_dashboard_url]).to eq('https://vercel.com/acme/my-shop')+ expect(response.body).to include('https://my-shop.vercel.app')+ end++ context 'when the deployed origin is already allowed' do+ before { create(:allowed_origin, store: store, origin: 'https://my-shop.vercel.app') }++ it 'flags it as allowed' do+ show++ expect(assigns[:deployment_origin_allowed]).to be true+ end+ end++ context 'with invalid callback params' do+ let(:params) do+ {+ 'deployment-url' => 'not a url',+ 'project-dashboard-url' => 'https://evil.example.com/phishing'+ }+ end++ it 'ignores them' do+ show++ expect(assigns[:deployment_origin]).to be_nil+ expect(assigns[:vercel_dashboard_url]).to be_nil+ end+ end+ end+ end++ describe 'PATCH #update' do+ subject(:update_storefront) { patch :update, params: params }++ let(:params) { { storefront_url: 'myshop.com', add_allowed_origin: '1' } }++ it 'saves the normalized storefront url and allows the origin' do+ expect { update_storefront }.to change { store.allowed_origins.count }.by(1)++ expect(store.reload.preferred_storefront_url).to eq('https://myshop.com')+ expect(store.allowed_origins.last.origin).to eq('https://myshop.com')+ expect(flash[:success]).to be_present+ expect(response).to redirect_to(spree.admin_storefront_path)+ end++ context 'without the add_allowed_origin flag' do+ let(:params) { { storefront_url: 'https://app.myshop.com' } }++ it 'only saves the preference' do+ expect { update_storefront }.not_to change(Spree::AllowedOrigin, :count)++ expect(store.reload.preferred_storefront_url).to eq('https://app.myshop.com')+ end+ end++ it 'overwrites an existing storefront url' do+ store.update!(preferred_storefront_url: 'https://old.example.com')++ update_storefront++ expect(store.reload.preferred_storefront_url).to eq('https://myshop.com')+ end++ context 'with an invalid url' do+ let(:params) { { storefront_url: 'not a url' } }++ it 'saves nothing and sets an error flash' do+ expect { update_storefront }.not_to change(Spree::AllowedOrigin, :count)++ expect(store.reload.preferred_storefront_url).to be_blank+ expect(flash[:error]).to be_present+ end+ end+ end++ describe 'POST #allow_origin' do+ subject(:allow_origin) { post :allow_origin, params: { origin: origin } }++ let(:origin) { 'https://my-shop.vercel.app' }++ it 'creates the allowed origin and sets the storefront url preference' do+ expect { allow_origin }.to change { store.allowed_origins.count }.by(1)++ expect(store.allowed_origins.last.origin).to eq(origin)+ expect(store.reload.preferred_storefront_url).to eq(origin)+ expect(flash[:success]).to be_present+ expect(response).to redirect_to(spree.admin_storefront_path)+ end++ it 'is idempotent for an already allowed origin' do+ create(:allowed_origin, store: store, origin: origin)++ expect { allow_origin }.not_to(change { store.allowed_origins.count })++ expect(flash[:success]).to be_present+ end++ it 'normalizes a bare host' do+ post :allow_origin, params: { origin: 'my-shop.vercel.app' }++ expect(store.allowed_origins.last.origin).to eq('https://my-shop.vercel.app')+ end++ context 'when the storefront url preference is already set' do+ before { store.update!(preferred_storefront_url: 'https://existing.example.com') }++ it 'does not overwrite it' do+ allow_origin++ expect(store.reload.preferred_storefront_url).to eq('https://existing.example.com')+ end+ end++ context 'with an invalid origin' do+ let(:origin) { 'not a url' }++ it 'creates nothing and sets an error flash' do+ expect { allow_origin }.not_to change(Spree::AllowedOrigin, :count)++ expect(flash[:error]).to be_present+ expect(store.reload.preferred_storefront_url).to be_blank+ end+ end+ end+enddiff --git a/spree/admin/spec/helpers/spree/admin/storefront_helper_spec.rb b/spree/admin/spec/helpers/spree/admin/storefront_helper_spec.rbnew file mode 100644index 0000000000..69a3a8d593--- /dev/null+++ b/spree/admin/spec/helpers/spree/admin/storefront_helper_spec.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Admin::StorefrontHelper, type: :helper do+ let(:store) { @default_store }+ let(:api_key) { create(:api_key, store: store) }++ describe '#vercel_deploy_url' do+ subject(:url) { helper.vercel_deploy_url(store, api_key) }++ let(:query) { Rack::Utils.parse_query(URI.parse(url).query) }++ it 'points at the Vercel clone flow for the storefront starter' do+ expect(url).to start_with('https://vercel.com/new/clone?')+ expect(query['repository-url']).to eq('https://github.com/spree/storefront')+ expect(query['project-name']).to eq("#{store.code}-storefront")+ end++ it 'requires and prefills the storefront environment variables' do+ expect(query['env']).to eq('SPREE_API_URL,SPREE_PUBLISHABLE_KEY')+ expect(JSON.parse(query['envDefaults'])).to eq(+ 'SPREE_API_URL' => store.formatted_url,+ 'SPREE_PUBLISHABLE_KEY' => api_key.token+ )+ end++ it 'redirects back to the admin storefront page' do+ expect(query['redirect-url']).to eq('http://test.host/admin/storefront')+ end+ end++ describe '#store_url_loopback?' do+ it 'is true for loopback store urls' do+ expect(helper.store_url_loopback?(build(:store, url: 'localhost:3000'))).to be true+ end++ it 'is false for public store urls' do+ expect(helper.store_url_loopback?(build(:store, url: 'shop.example.com'))).to be false+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/stores/setup.rb b/spree/core/app/models/concerns/spree/stores/setup.rbindex e385ab403f..e61739f8fe 100644--- a/spree/core/app/models/concerns/spree/stores/setup.rb+++ b/spree/core/app/models/concerns/spree/stores/setup.rb@@ -13,6 +13,8 @@ module Spreeproducts.any?when :set_customer_support_emailcustomer_support_email.present?+ when :setup_storefront+ storefront_setup?endend@@ -28,6 +30,7 @@ module Spree@setup_tasks_list << :add_products@setup_tasks_list << :set_customer_support_email@setup_tasks_list << :setup_taxes_collection+ @setup_tasks_list << :setup_storefront@setup_tasks_listend@@ -47,6 +50,28 @@ module Spreedef payment_method_setup?payment_methods.active.where.not(type: Spree::PaymentMethod::StoreCredit.to_s).any?end++ # A storefront counts as set up once an active publishable key has actually+ # authenticated a Store API request and a storefront is connected.+ def storefront_setup?+ storefront_publishable_key_used? && storefront_connected?+ end++ def storefront_publishable_key_used?+ api_keys.active.publishable.where.not(last_used_at: nil).exists?+ end++ # A non-loopback allowed origin (web storefronts) or an explicit storefront+ # URL (mobile apps and other clients that don't need CORS) both count as a+ # connected storefront; the `http://localhost` origin seeded on install+ # doesn't.+ def storefront_connected?+ storefront_origin_added? || preferred_storefront_url.present?+ end++ def storefront_origin_added?+ allowed_origins.reject(&:loopback?).any?+ endendendenddiff --git a/spree/core/app/models/spree/allowed_origin.rb b/spree/core/app/models/spree/allowed_origin.rbindex 0904ec8e90..325c49c083 100644--- a/spree/core/app/models/spree/allowed_origin.rb+++ b/spree/core/app/models/spree/allowed_origin.rb@@ -32,6 +32,15 @@ module Spreenilend+ # Whether this origin points at a loopback/development host ({LOOPBACK_HOSTS}),+ # e.g. the `http://localhost` origin seeded on install. Loopback origins are+ # ignored when deciding if a real storefront has been connected to the store.+ #+ # @return [Boolean]+ def loopback?+ LOOPBACK_HOSTS.include?(self.class.parse_origin(origin)&.dig(:host))+ end+# Returns true if the given URL's origin matches this stored origin.## Scheme and host must match exactly (host comparison is case- and trailing-dot-diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 6d858992e6..30444e2ac0 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -51,6 +51,9 @@ module Spreepreference :guest_checkout, :boolean, default: true# Store-level fallback for the channel-owned `storefront_access` posture.preference :storefront_access, :string, default: 'public'+ # Canonical storefront origin used in customer-facing emails and links,+ # e.g. "https://myshop.com" — see #storefront_url for the fallback chain.+ preference :storefront_url, :stringpreference :special_instructions_enabled, :boolean, default: falsepreference :stock_reservation_ttl_minutes, :integer, default: 10# Address preferences@@ -281,11 +284,15 @@ module Spreeend# Returns the storefront origin URL for use in customer-facing emails and links.- # Uses the first allowed origin if configured, otherwise falls back to formatted_url.+ # Uses the `storefront_url` preference when set, then the oldest non-loopback+ # allowed origin (the `http://localhost` origin seeded on install must never+ # leak into customer emails), otherwise falls back to formatted_url.## @return [String] e.g. "https://myshop.com"def storefront_url- allowed_origins.order(:created_at).pick(:origin) || formatted_url+ preferred_storefront_url.presence ||+ allowed_origins.order(:created_at).reject(&:loopback?).first&.origin ||+ formatted_urlend# Returns true if the given URL's origin matches one of the store's allowed origins.diff --git a/spree/core/spec/models/spree/allowed_origin_spec.rb b/spree/core/spec/models/spree/allowed_origin_spec.rbindex 657900ae12..e6eb721a9f 100644--- a/spree/core/spec/models/spree/allowed_origin_spec.rb+++ b/spree/core/spec/models/spree/allowed_origin_spec.rb@@ -80,6 +80,17 @@ RSpec.describe Spree::AllowedOrigin, type: :model doendend+ describe '#loopback?' do+ it 'is true for loopback hosts regardless of port' do+ expect(build(:allowed_origin, store: store, origin: 'http://localhost').loopback?).to be true+ expect(build(:allowed_origin, store: store, origin: 'http://127.0.0.1:3000').loopback?).to be true+ end++ it 'is false for public hosts' do+ expect(build(:allowed_origin, store: store, origin: 'https://myshop.com').loopback?).to be false+ end+ end+describe '#matches?' dosubject(:allowed_origin) { build(:allowed_origin, store: store, origin: stored) }diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rbindex 1753bc6529..0fb58c222f 100644--- a/spree/core/spec/models/spree/store_spec.rb+++ b/spree/core/spec/models/spree/store_spec.rb@@ -900,6 +900,17 @@ describe Spree::Store, type: :model, without_global_store: true dodescribe '#storefront_url' dolet(:store) { create(:store, url: 'backend.example.com') }+ context 'when the storefront_url preference is set' do+ before do+ store.update!(preferred_storefront_url: 'https://preferred.example.com')+ create(:allowed_origin, store: store, origin: 'https://shop.example.com', created_at: 1.day.ago)+ end++ it 'returns the preference over allowed origins' do+ expect(store.storefront_url).to eq('https://preferred.example.com')+ end+ end+context 'when allowed origins exist' dobefore docreate(:allowed_origin, store: store, origin: 'https://shop.example.com', created_at: 1.day.ago)@@ -914,6 +925,22 @@ describe Spree::Store, type: :model, without_global_store: true doexpect(store.storefront_url).to eq('https://shop.example.com')end++ it 'skips loopback origins even when they are oldest' do+ create(:allowed_origin, store: store, origin: 'http://localhost:3001', created_at: 1.week.ago)++ expect(store.storefront_url).to eq('https://shop.example.com')+ end+ end++ context 'when only loopback origins exist' do+ before do+ create(:allowed_origin, store: store, origin: 'http://localhost:3001')+ end++ it 'falls back to formatted_url' do+ expect(store.storefront_url).to eq(store.formatted_url)+ endendcontext 'when no allowed origins exist' do@@ -922,4 +949,65 @@ describe Spree::Store, type: :model, without_global_store: true doendendend++ describe 'storefront setup task' do+ let(:store) { create(:store) }++ it 'is included in the setup tasks list' do+ expect(store.setup_tasks_list).to include(:setup_storefront)+ end++ describe '#storefront_setup?' do+ subject { store.storefront_setup? }++ context 'with a used publishable key and a non-loopback allowed origin' do+ before do+ create(:api_key, store: store, last_used_at: 1.hour.ago)+ create(:allowed_origin, store: store, origin: 'https://shop.example.com')+ end++ it { is_expected.to be true }++ it 'marks the setup task as done' do+ expect(store.setup_task_done?(:setup_storefront)).to be true+ end+ end++ context 'when the publishable key has never been used' do+ before do+ create(:api_key, store: store)+ create(:allowed_origin, store: store, origin: 'https://shop.example.com')+ end++ it { is_expected.to be false }+ end++ context 'when the used publishable key is revoked' do+ before do+ create(:api_key, :revoked, store: store, last_used_at: 1.hour.ago)+ create(:allowed_origin, store: store, origin: 'https://shop.example.com')+ end++ it { is_expected.to be false }+ end++ context 'when only a loopback origin exists' do+ before do+ create(:api_key, store: store, last_used_at: 1.hour.ago)+ create(:allowed_origin, store: store, origin: 'http://localhost')+ end++ it { is_expected.to be false }+ end++ context 'when connected via the storefront_url preference only' do+ before do+ create(:api_key, store: store, last_used_at: 1.hour.ago)+ store.update!(preferred_storefront_url: 'https://app.example.com')+ end++ it { is_expected.to be true }+ end+ end+ endend