Building a Shopify app with Laravel · Part 4 of 6
The admin UI with React, TypeScript and Polaris 2
A reviews table, an add-review modal with product search and a settings page on Polaris 2 web components under React 19, with the four places the combination bites and how to get round each.
By Abhishek Fouzdar · Updated
The endpoints from part 3 get their interface: a reviews table with a status filter, pagination and moderation actions, an add-review modal with product search, and a settings page. It is React 19 with TypeScript, and the components are Polaris 2 web components loaded from Shopify's CDN, so the app ships a bundle of 128 KB gzipped (437 KB raw) and looks like the rest of the admin without a design system of its own.

Polaris now means web components
Polaris used to be a React component library. Since 2025 it is a set of custom elements, <s-page>, <s-table>, <s-button> and so on, served by one script from the CDN and usable from any framework or none. Version 2.0 shipped on 22 October 2026 and follows the admin's current appearance; the polaris-2.js script in part 1's view is what selects it. The React library is on its way out and does not work inside the new admin chrome, so there is nothing to migrate from: this part starts on the web components.
Three consequences for a React app. Custom elements need React 19, which assigns unknown props as element properties and wires onClick, onInput and onChange to the elements' native events; React 18 does neither. The elements are not imported, so TypeScript needs a types package to know that <s-table> exists and what it accepts. And a handful of things render differently from what a React developer expects; the last section lists the ones that bit.
Tooling
Laravel 13 ships Vite 8 and Tailwind. Tailwind goes, since Polaris supplies the styling, and React, TypeScript and the two Shopify type packages come in.
npm install react react-dom
npm install -D typescript @types/react @types/react-dom @vitejs/plugin-react @shopify/polaris-types @shopify/app-bridge-types
npm uninstall tailwindcss @tailwindcss/vite
rm resources/css/app.css resources/js/app.js resources/js/bootstrap.js vite.config.js
tsconfig.json, with both type packages registered globally, which is how their READMEs ask to be used:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["@shopify/polaris-types", "@shopify/app-bridge-types"]
},
"include": ["resources/js"]
}
vite.config.ts:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
laravel({ input: ['resources/js/main.tsx'], refresh: true }),
react(),
],
});
One decision about the dev loop. Vite's dev server with hot reloading serves scripts from http://localhost:5173, and the App Home page is an HTTPS iframe inside the admin, which blocks that as mixed content. Instead, vite build --watch rebuilds the bundle on every save into public/build, and a reload shows it. Three processes now need to run under shopify app dev: the web server, the queue worker from part 3, and the watcher. Laravel already depends on concurrently, which runs them side by side and kills the rest when one dies. The command lives in package.json, for a reason that the last section explains.
package.json scripts:
"dev": "concurrently --kill-others --names web,queue,vite \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"vite build --watch\"",
"build": "vite build",
"typecheck": "tsc --noEmit"
shopify.web.toml:
# Tells the Shopify CLI how to run this app during `shopify app dev`. The CLI starts the
# dev command below, sets SERVER_PORT (which `php artisan serve` reads), and tunnels to it.
# `npm run dev` (see package.json) starts three processes side by side: the web server,
# the queue worker for the metafield job, and Vite rebuilding the admin UI on every save.
name = "ReviewMini"
roles = ["frontend", "backend"]
webhooks_path = "/api/webhooks"
[commands]
dev = "npm run dev"
The Blade view becomes a mount point.
resources/views/app.blade.php:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ReviewMini</title>
{{-- App Bridge reads the client ID from this meta tag. --}}
<meta name="shopify-api-key" content="{{ config('shopify.api_key') }}">
<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
<script src="https://cdn.shopify.com/shopifycloud/polaris-2.js"></script>
@vite('resources/js/main.tsx')
</head>
<body>
<div id="app"></div>
</body>
</html>
The code
Types for what the API returns, and a client that knows nothing about tokens, because App Bridge adds the Bearer header to every same-origin fetch() itself. The client turns a 422 into an ApiError carrying Laravel's per-field messages, which the forms show next to the right field.
resources/js/types.ts:
export type ReviewStatus = 'pending' | 'approved' | 'rejected';
export interface Review {
id: number;
product_id: string;
product_title: string;
author_name: string;
author_email: string | null;
rating: number;
title: string | null;
body: string;
status: ReviewStatus;
created_at: string;
}
export interface Paginated<T> {
data: T[];
current_page: number;
last_page: number;
total: number;
}
export interface Product {
id: string;
title: string;
handle: string;
image: string | null;
}
export interface Settings {
auto_approve: boolean;
widget_title: string;
}
export interface ShopInfo {
name: string;
myshopifyDomain: string;
currencyCode: string;
plan: { publicDisplayName: string; partnerDevelopment: boolean };
}
resources/js/api.ts:
/**
* The app's JSON API. App Bridge intercepts same-origin fetch() calls and adds the
* ID token as an Authorization header, so nothing here deals with tokens.
*/
export class ApiError extends Error {
constructor(
public status: number,
message: string,
public errors: Record<string, string[]> = {},
) {
super(message);
}
}
export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(`/api${path}`, {
...init,
headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...init.headers },
});
if (response.status === 204) {
return undefined as T;
}
const body = await response.json().catch(() => ({}));
if (!response.ok) {
throw new ApiError(response.status, body.message ?? response.statusText, body.errors ?? {});
}
return body as T;
}
export const get = <T>(path: string) => api<T>(path);
export const post = <T>(path: string, data: unknown) => api<T>(path, { method: 'POST', body: JSON.stringify(data) });
export const put = <T>(path: string, data: unknown) => api<T>(path, { method: 'PUT', body: JSON.stringify(data) });
export const patch = <T>(path: string, data: unknown) => api<T>(path, { method: 'PATCH', body: JSON.stringify(data) });
export const destroy = (path: string) => api<void>(path, { method: 'DELETE' });
Two screens and no router. The admin owns the chrome around the iframe; the app renders what goes inside it, and a view state is enough for two pages. The entry file is main.tsx rather than app.tsx, because TypeScript refuses app.tsx and App.tsx in the same directory on a case-insensitive lookup.
resources/js/main.tsx:
import { createRoot } from 'react-dom/client';
import { App } from './App';
createRoot(document.getElementById('app')!).render(<App />);
resources/js/App.tsx:
import { useState } from 'react';
import { ReviewsPage } from './pages/ReviewsPage';
import { SettingsPage } from './pages/SettingsPage';
type View = 'reviews' | 'settings';
/**
* Two screens, no router: the reviews list and the settings form. App Bridge owns the
* admin chrome around the iframe; the app only renders what goes inside it.
*/
export function App() {
const [view, setView] = useState<View>('reviews');
return view === 'reviews'
? <ReviewsPage onOpenSettings={() => setView('settings')} />
: <SettingsPage onBack={() => setView('reviews')} />;
}
The reviews page. <s-table> takes its filter controls in a filters slot and handles pagination itself, given paginate, the two has…Page flags and the two events. listSlot on the headers tells the table which columns to keep when it collapses to a list on narrow screens. The action buttons are an inline <s-stack>, for a reason in the last section.
resources/js/pages/ReviewsPage.tsx:
import { useCallback, useEffect, useState } from 'react';
import { destroy, get, patch } from '../api';
import type { Paginated, Review, ReviewStatus } from '../types';
import { AddReviewModal } from '../components/AddReviewModal';
import { Stars } from '../components/Stars';
const tones: Record<ReviewStatus, 'success' | 'warning' | 'critical'> = {
approved: 'success',
pending: 'warning',
rejected: 'critical',
};
export function ReviewsPage({ onOpenSettings }: { onOpenSettings: () => void }) {
const [status, setStatus] = useState<ReviewStatus | ''>('');
const [page, setPage] = useState(1);
const [reviews, setReviews] = useState<Paginated<Review> | null>(null);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setLoading(true);
const params = new URLSearchParams({ page: String(page), ...(status ? { status } : {}) });
setReviews(await get<Paginated<Review>>(`/reviews?${params}`));
setLoading(false);
}, [page, status]);
useEffect(() => { load(); }, [load]);
async function moderate(review: Review, next: ReviewStatus) {
await patch(`/reviews/${review.id}`, { status: next });
shopify.toast.show(`Review ${next}`);
load();
}
async function remove(review: Review) {
await destroy(`/reviews/${review.id}`);
shopify.toast.show('Review deleted');
load();
}
return (
<s-page heading="Reviews">
<s-button slot="primary-action" variant="primary" commandFor="add-review" command="--show">Add review</s-button>
<s-button slot="secondary-actions" onClick={onOpenSettings}>Settings</s-button>
<s-section>
<s-table
loading={loading}
paginate
hasPreviousPage={page > 1}
hasNextPage={reviews !== null && page < reviews.last_page}
onPreviousPage={() => setPage(page - 1)}
onNextPage={() => setPage(page + 1)}
>
<s-select slot="filters" label="Status" labelAccessibilityVisibility="exclusive" value={status} onChange={(e) => { setStatus(e.currentTarget.value as ReviewStatus | ''); setPage(1); }}>
<s-option value="">All statuses</s-option>
<s-option value="pending">Pending</s-option>
<s-option value="approved">Approved</s-option>
<s-option value="rejected">Rejected</s-option>
</s-select>
<s-table-header-row>
<s-table-header listSlot="primary">Product</s-table-header>
<s-table-header listSlot="secondary">Review</s-table-header>
<s-table-header>Rating</s-table-header>
<s-table-header listSlot="kicker">Status</s-table-header>
<s-table-header listSlot="inline">Actions</s-table-header>
</s-table-header-row>
<s-table-body>
{reviews?.data.map((review) => (
<s-table-row key={review.id}>
<s-table-cell>{review.product_title}</s-table-cell>
<s-table-cell>
<s-stack gap="small-300">
<s-text type="strong">{review.title ?? `${review.author_name} wrote`}</s-text>
<s-text>{review.body}</s-text>
<s-text color="subdued">{review.author_name}</s-text>
</s-stack>
</s-table-cell>
<s-table-cell><Stars rating={review.rating} /></s-table-cell>
<s-table-cell><s-badge tone={tones[review.status]}>{review.status}</s-badge></s-table-cell>
<s-table-cell>
<s-stack direction="inline" gap="small">
{review.status !== 'approved' && <s-button onClick={() => moderate(review, 'approved')}>Approve</s-button>}
{review.status !== 'rejected' && <s-button onClick={() => moderate(review, 'rejected')}>Reject</s-button>}
<s-button tone="critical" variant="tertiary" onClick={() => remove(review)}>Delete</s-button>
</s-stack>
</s-table-cell>
</s-table-row>
))}
</s-table-body>
</s-table>
{reviews !== null && reviews.total === 0 && !loading && (
<s-paragraph>No reviews yet. Add one above, or wait for the storefront form in part 6.</s-paragraph>
)}
</s-section>
<AddReviewModal onCreated={() => { setPage(1); load(); }} />
</s-page>
);
}
resources/js/components/Stars.tsx:
export function Stars({ rating }: { rating: number }) {
return <s-text>{'★'.repeat(rating) + '☆'.repeat(5 - rating)}</s-text>;
}
The modal. Polaris modals open and close declaratively: a button with commandFor pointing at the modal's id and a command of --show or --hide. For closing after a successful save the code calls hideOverlay() on a ref; the types package provides HTMLElementTagNameMap['s-modal'] for that. The onShow handler runs the first product search when the modal opens. Product search is the one place the admin UI calls the Admin API, through the app's endpoint from part 3.

resources/js/components/AddReviewModal.tsx:
import { useRef, useState } from 'react';
import { ApiError, get, post } from '../api';
import type { Product, Review, ReviewStatus } from '../types';
interface Props {
onCreated: (review: Review) => void;
}
interface Form {
author_name: string;
author_email: string;
rating: string;
title: string;
body: string;
status: ReviewStatus;
}
const empty: Form = { author_name: '', author_email: '', rating: '5', title: '', body: '', status: 'approved' };
/** Polaris fields hand back a DOM event; the value lives on the element that fired it. */
type FieldEvent = { currentTarget: { value: string } };
/**
* A merchant-entered review, for imports and for trying the app before the storefront
* form exists. Product search goes through the app's API, which asks the Admin API.
*/
export function AddReviewModal({ onCreated }: Props) {
const modal = useRef<HTMLElementTagNameMap['s-modal']>(null);
const [search, setSearch] = useState('');
const [products, setProducts] = useState<Product[]>([]);
const [product, setProduct] = useState<Product | null>(null);
const [form, setForm] = useState<Form>(empty);
const [errors, setErrors] = useState<Record<string, string[]>>({});
const [saving, setSaving] = useState(false);
const set = (name: keyof Form) => (e: FieldEvent) => setForm({ ...form, [name]: e.currentTarget.value });
const error = (name: string) => errors[name]?.[0];
async function searchProducts(query: string) {
setSearch(query);
setProducts(await get<Product[]>(`/products?query=${encodeURIComponent(query)}`));
}
async function save() {
setSaving(true);
setErrors({});
try {
const review = await post<Review>('/reviews', {
...form,
rating: Number(form.rating),
author_email: form.author_email || null,
title: form.title || null,
product_id: product?.id,
product_title: product?.title,
});
onCreated(review);
shopify.toast.show('Review added');
setForm(empty);
setProduct(null);
modal.current?.hideOverlay();
} catch (e) {
if (e instanceof ApiError && e.status === 422) {
setErrors(e.errors);
} else {
shopify.toast.show('Could not save the review', { isError: true });
}
} finally {
setSaving(false);
}
}
return (
<s-modal id="add-review" heading="Add a review" ref={modal} onShow={() => searchProducts('')}>
<s-stack gap="base">
<s-search-field
label="Product"
placeholder="Search products"
value={search}
error={error('product_id')}
onInput={(e) => searchProducts(e.currentTarget.value)}
/>
<s-select
label="Matching products"
value={product?.id ?? ''}
onChange={(e) => setProduct(products.find((p) => p.id === e.currentTarget.value) ?? null)}
>
<s-option value="">Choose a product</s-option>
{products.map((p) => <s-option key={p.id} value={p.id}>{p.title}</s-option>)}
</s-select>
<s-text-field label="Reviewer name" name="author_name" value={form.author_name} error={error('author_name')} onInput={set('author_name')} />
<s-email-field label="Reviewer email (optional)" name="author_email" value={form.author_email} error={error('author_email')} onInput={set('author_email')} />
<s-select label="Rating" name="rating" value={form.rating} error={error('rating')} onChange={set('rating')}>
{[5, 4, 3, 2, 1].map((n) => <s-option key={n} value={String(n)}>{'★'.repeat(n)}</s-option>)}
</s-select>
<s-text-field label="Title (optional)" name="title" value={form.title} error={error('title')} onInput={set('title')} />
<s-text-area label="Review" name="body" rows={4} value={form.body} error={error('body')} onInput={set('body')} />
<s-select label="Status" name="status" value={form.status} onChange={set('status')}>
<s-option value="approved">Approved</s-option>
<s-option value="pending">Pending</s-option>
<s-option value="rejected">Rejected</s-option>
</s-select>
</s-stack>
<s-button slot="primary-action" variant="primary" loading={saving} onClick={save}>Save review</s-button>
<s-button slot="secondary-actions" commandFor="add-review" command="--hide">Cancel</s-button>
</s-modal>
);
}
Settings. <s-switch> reports its state on checked, text fields on value, both read from event.currentTarget. Toasts come from App Bridge's global shopify object, typed by @shopify/app-bridge-types; the admin renders them outside the iframe.
resources/js/pages/SettingsPage.tsx:
import { useEffect, useState } from 'react';
import { ApiError, get, put } from '../api';
import type { Settings } from '../types';
export function SettingsPage({ onBack }: { onBack: () => void }) {
const [settings, setSettings] = useState<Settings | null>(null);
const [errors, setErrors] = useState<Record<string, string[]>>({});
const [saving, setSaving] = useState(false);
useEffect(() => { get<Settings>('/settings').then(setSettings); }, []);
async function save() {
if (!settings) return;
setSaving(true);
setErrors({});
try {
setSettings(await put<Settings>('/settings', settings));
shopify.toast.show('Settings saved');
} catch (e) {
if (e instanceof ApiError && e.status === 422) setErrors(e.errors);
else shopify.toast.show('Could not save settings', { isError: true });
} finally {
setSaving(false);
}
}
return (
<s-page heading="Settings">
<s-button slot="secondary-actions" onClick={onBack}>Back to reviews</s-button>
<s-button slot="primary-action" variant="primary" loading={saving} disabled={!settings} onClick={save}>Save</s-button>
<s-section heading="Moderation">
{settings ? (
<s-stack gap="base">
<s-switch
label="Publish storefront reviews automatically"
details="Off: new reviews wait in Pending until you approve them."
name="auto_approve"
checked={settings.auto_approve}
onChange={(e) => setSettings({ ...settings, auto_approve: e.currentTarget.checked })}
/>
<s-text-field
label="Storefront heading"
name="widget_title"
value={settings.widget_title}
error={errors.widget_title?.[0]}
onInput={(e) => setSettings({ ...settings, widget_title: e.currentTarget.value })}
/>
</s-stack>
) : <s-spinner accessibilityLabel="Loading settings" />}
</s-section>
</s-page>
);
}
Running it
npm run typecheck && npm run build
shopify app dev --store saanjh-living.myshopify.com --tunnel-url https://reviewmini.shipbytes.dev:3000
[vite] built in 220ms.
[web] INFO Server running on [http://127.0.0.1:42043].
✅ Ready, watching for changes in your app
In the admin: the two reviews from part 3 in the table, the modal finding "Bhadohi Wool Rug" for "rug", a third review saved as pending with a toast, approved from the table with another toast, and the settings page saving a heading. Each of those is one request to the endpoints from part 3; the CLI's log shows them as they happen.
The App Home test from part 2 looked for the placeholder text; it now checks for the mount point and the meta tag instead.
tests/Feature/AppHomeTest.php, the changed assertion:
$response->assertOk();
$response->assertSee('<div id="app"></div>', escape: false);
$response->assertSee('<meta name="shopify-api-key" content="test-client-id">', escape: false);
When it goes wrong
The table renders but a cell with <s-button-group> inside it is empty. Button groups do not render inside table cells. An inline <s-stack> with the buttons in it does.
A button in <s-page>'s breadcrumb-actions slot does not appear. An icon-only button in that slot rendered nothing in Polaris 2.0.0 whatever the icon name. A labelled button in secondary-actions works and reads better anyway.
shopify app dev starts, then every process exits with code 2 or 127. The CLI splits the dev command in shopify.web.toml on spaces and ignores quotes, so a concurrently command with quoted arguments comes apart. Put the command in an npm script and set dev = "npm run dev".
Scripts blocked, blank iframe, console shows mixed content. The Vite dev server is running and Laravel's @vite directive found its public/hot file. Stop it, delete public/hot, use vite build --watch.
TS1149: File name differs from already included file name only in casing. app.tsx next to App.tsx. Rename the entry file.
TS2590: Expression produces a union type that is too complex to represent. Spreading an object of props onto a Polaris element. Write the props out; the element types are large unions and a spread makes TypeScript compute all of them.
onChange never fires on an <s-text-field>. It fires on commit, on blur or Enter. Use onInput for every keystroke. For <s-select> and <s-switch>, onChange fires immediately.
Everything works but TypeScript does not know shopify.toast. @shopify/app-bridge-types is not in the types array of tsconfig.json.
Part 5 turns the app around: instead of answering the admin, it answers Shopify, with webhooks, an Events subscription and the privacy topics every app has to handle.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
4 / 6- OverviewBuilding a Shopify app with Laravel
- Part 1Project, CLI, app record and tunnel
- Part 2Authentication with ID tokens and expiring access tokens
- Part 3Reviews, settings, product search and the rating metafields
- Part 4The admin UI with React, TypeScript and Polaris 2
- Part 5Webhooks, Events and the privacy topics
- Part 6App proxy, theme app extension and the end-to-end check