Building a Shopify app with Laravel · Part 6 of 6
App proxy, theme app extension and the end-to-end check
A signed proxy route the storefront calls, a theme app extension that reads the rating metafields in Liquid, and a review that goes from the product page to the admin and back.
By Abhishek Fouzdar · Updated
The last surface is the one shoppers see. A merchant adds a block to the product page in the theme editor; the block shows the average rating from the metafields of part 3, lists the approved reviews, and takes new ones. The reviews travel through an app proxy, a signed route Shopify forwards from the shop's own domain. The part ends with a review typed on the storefront, approved in the admin, and counted on the storefront, which exercises every part of the series in one loop.

Two more words
App proxy. A path on the shop's domain, /apps/reviews/… here, that Shopify forwards to a URL of yours, adding a signature over the query string. The storefront can call the app without cross-origin requests, and the app can trust which shop the call came from. A logged-in customer's ID comes along too.
Theme app extension. A set of Liquid blocks, assets and locale files that your app contributes to any theme. The merchant places a block in the theme editor; the theme never has to be edited by hand, and the block keeps working when the merchant switches themes.
The proxy side of the app
Declare the proxy in shopify.app.toml. Requests to https://<shop>/apps/reviews/<path> become requests to https://reviewmini.shipbytes.dev/storefront/<path>.
[app_proxy]
url = "https://reviewmini.shipbytes.dev/storefront"
subpath = "reviews"
prefix = "apps"
The signature is an HMAC-SHA256, hex encoded, of the query parameters sorted by name and joined as key=value with no separator, including a timestamp that must be within 90 seconds. The package checks all of it; the middleware's own job is to look up the shop and refuse if the app is not installed there.
app/Http/Middleware/VerifyAppProxy.php:
<?php
namespace App\Http\Middleware;
use App\Models\Shop;
use App\Shopify\Adapter;
use Closure;
use Illuminate\Http\Request;
use Shopify\App\ShopifyApp;
use Symfony\Component\HttpFoundation\Response;
/**
* Requests that reach the app through the app proxy: a visitor's browser calls
* /apps/reviews/... on the storefront, Shopify forwards it here with a signature over
* the query string. The shop and, when a customer is logged in, their ID are trusted;
* nothing else in the request is.
*/
class VerifyAppProxy
{
public function __construct(private ShopifyApp $shopify) {}
public function handle(Request $request, Closure $next): Response
{
$result = $this->shopify->verifyAppProxyReq(Adapter::req($request));
if (! $result->ok) {
return Adapter::response($result);
}
$shop = Shop::where('shop', $result->shop)->whereNotNull('access_token')->first();
if ($shop === null) {
return response()->json(['message' => 'App not installed'], 404);
}
$request->attributes->set('shop', $shop);
$request->attributes->set('customerId', $result->loggedInCustomerId);
return $next($request);
}
}
The storefront routes live in their own file, under the api middleware group (no session, no CSRF, since the signature is the authentication) and the proxy middleware. Liquid knows a product by its numeric ID; the app stores global IDs; the controller joins the two.
routes/storefront.php:
<?php
use App\Http\Controllers\Storefront\ReviewController;
use Illuminate\Support\Facades\Route;
// Reached only through the app proxy: Shopify forwards https://<shop>/apps/reviews/...
// to https://<app>/storefront/... and signs the request. No session, no CSRF token;
// the signature is the authentication.
Route::prefix('storefront')->middleware(['api', 'shopify.app-proxy'])->group(function () {
Route::get('/products/{productId}', [ReviewController::class, 'index']);
Route::post('/products/{productId}/reviews', [ReviewController::class, 'store']);
});
app/Http/Controllers/Storefront/ReviewController.php:
<?php
namespace App\Http\Controllers\Storefront;
use App\Http\Controllers\Controller;
use App\Jobs\SyncProductRating;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* What the storefront block reads and writes. Liquid gives it the numeric product ID;
* the app stores the global ID, so the two are joined here.
*/
class ReviewController extends Controller
{
public function index(Request $request, int $productId): JsonResponse
{
$shop = $request->attributes->get('shop');
$reviews = $shop->reviews()
->where('product_id', $this->gid($productId))
->where('status', 'approved')
->latest()
->limit(50)
->get()
->map(fn ($review) => [
'rating' => $review->rating,
'title' => $review->title,
'body' => $review->body,
'author_name' => $review->author_name,
'created_at' => $review->created_at->toFormattedDateString(),
]);
return response()->json(['reviews' => $reviews]);
}
public function store(Request $request, int $productId): JsonResponse
{
$shop = $request->attributes->get('shop');
$data = $request->validate([
'author_name' => ['required', 'string', 'max:100'],
'author_email' => ['nullable', 'email', 'max:255'],
'rating' => ['required', 'integer', 'between:1,5'],
'title' => ['nullable', 'string', 'max:150'],
'body' => ['required', 'string', 'max:3000'],
'product_title' => ['required', 'string', 'max:255'],
]);
$review = $shop->reviews()->create([
...$data,
'product_id' => $this->gid($productId),
'status' => $shop->settings->auto_approve ? 'approved' : 'pending',
]);
if ($review->status === 'approved') {
SyncProductRating::dispatch($shop, $review->product_id);
}
return response()->json(['status' => $review->status], 201);
}
private function gid(int $productId): string
{
return "gid://shopify/Product/{$productId}";
}
}
A visitor's review is created with the status the shop's settings say: pending by default, approved when the merchant turned on automatic publishing in part 4. Only approved reviews go out, and the reviewer's email never does.
bootstrap/app.php registers the file and the alias:
<?php
use App\Http\Middleware\AuthenticateAppHome;
use App\Http\Middleware\VerifyAppProxy;
use App\Http\Middleware\VerifyShopifyWebhook;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
then: function () {
Route::group([], base_path('routes/storefront.php'));
},
)
->withMiddleware(function (Middleware $middleware): void {
// TLS ends at the tunnel (and later at the load balancer); the app itself speaks
// plain HTTP. Trusting the forwarded headers keeps generated URLs on https.
$middleware->trustProxies(at: '*');
$middleware->alias([
'shopify.app-home' => AuthenticateAppHome::class,
'shopify.webhook' => VerifyShopifyWebhook::class,
'shopify.app-proxy' => VerifyAppProxy::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
);
})->create();
The theme app extension
The CLI generates the skeleton inside the app's extensions/ directory.
shopify app generate extension --template theme_app_extension --name review-block
│ Your extension was created in extensions/review-block. │
It comes with a sample star-rating block, a snippet and a thumbs-up image. Delete the sample block and the image; replace the rest.
The block itself. Liquid renders what Shopify already knows at request time: the product, and the two metafields the app keeps in sync. The reviews themselves come from the proxy, loaded by the script. target = "content" is the placement the current theme architecture uses for app blocks inside the page; the merchant decides where. The product setting with autofill makes the block pick up the page's product without configuration. Strings go through the locale file so that the block can be translated.
extensions/review-block/blocks/reviews.liquid:
{%- comment -%}
The storefront review block. Liquid renders what Shopify already knows (the product,
the rating metafields the app keeps in sync); the script fetches the reviews
themselves through the app proxy and posts new ones the same way.
{%- endcomment -%}
{%- assign product = block.settings.product -%}
{%- assign rating = product.metafields['$app:reviewmini'].rating_average.value -%}
{%- assign rounded = rating | round -%}
{%- assign count = product.metafields['$app:reviewmini'].rating_count.value | default: 0 -%}
<div
class="reviewmini"
data-reviewmini
data-product-id="{{ product.id }}"
data-product-title="{{ product.title | escape }}"
data-endpoint="{{ routes.root_url | append: 'apps/reviews' | replace: '//', '/' }}"
>
<h2 class="reviewmini__heading">{{ block.settings.heading | default: 'Customer reviews' }}</h2>
<p class="reviewmini__summary">
{%- if count > 0 -%}
{%- render 'stars', rating: rounded -%}
{{ rating | round: 1 }} {{ 'reviews.summary.out_of' | t }} · {{ count }} {{ 'reviews.summary.reviews' | t }}
{%- else -%}
{{ 'reviews.summary.none' | t }}
{%- endif -%}
</p>
<ol class="reviewmini__list" data-reviewmini-list aria-live="polite"></ol>
{%- if block.settings.show_form -%}
<form class="reviewmini__form" data-reviewmini-form>
<h3>{{ 'reviews.form.heading' | t }}</h3>
<label>{{ 'reviews.form.name' | t }} <input name="author_name" required maxlength="100"></label>
<label>{{ 'reviews.form.email' | t }} <input name="author_email" type="email" maxlength="255"></label>
<label>{{ 'reviews.form.rating' | t }}
<select name="rating" required>
<option value="5">★★★★★</option>
<option value="4">★★★★</option>
<option value="3">★★★</option>
<option value="2">★★</option>
<option value="1">★</option>
</select>
</label>
<label>{{ 'reviews.form.title' | t }} <input name="title" maxlength="150"></label>
<label>{{ 'reviews.form.body' | t }} <textarea name="body" required rows="4" maxlength="3000"></textarea></label>
<button type="submit" class="button">{{ 'reviews.form.submit' | t }}</button>
<p class="reviewmini__status" data-reviewmini-status role="status"></p>
</form>
{%- endif -%}
</div>
<link rel="stylesheet" href="{{ 'reviews.css' | asset_url }}">
<script src="{{ 'reviews.js' | asset_url }}" defer></script>
{% schema %}
{
"name": "Product reviews",
"target": "content",
"settings": [
{ "type": "product", "id": "product", "label": "Product", "autofill": true },
{ "type": "text", "id": "heading", "label": "Heading", "default": "Customer reviews" },
{ "type": "checkbox", "id": "show_form", "label": "Show the review form", "default": true }
]
}
{% endschema %}
The metafield read is the whole point of part 3's job. product.metafields['$app:reviewmini'].rating_average.value works in the app's own extension without hard-coding the app ID that the namespace carries in API responses.
extensions/review-block/snippets/stars.liquid:
<span class="reviewmini__stars" aria-label="{{ rating }} {{ 'reviews.summary.out_of' | t }}">
{%- for i in (1..rating) -%}★{%- endfor -%}
{%- assign blank_stars = 5 | minus: rating -%}
{%- for i in (1..blank_stars) -%}☆{%- endfor -%}
</span>
extensions/review-block/locales/en.default.json:
{
"reviews": {
"summary": {
"out_of": "out of 5",
"reviews": "reviews",
"none": "No reviews yet. Be the first."
},
"form": {
"heading": "Write a review",
"name": "Your name",
"email": "Email (not published)",
"rating": "Rating",
"title": "Title",
"body": "Review",
"submit": "Submit review",
"thanks": "Thanks! Your review is published.",
"pending": "Thanks! Your review will appear once the shop approves it.",
"error": "Sorry, that did not go through. Check the fields and try again."
}
}
}
The script talks only to the proxy path, which the block passes in as a data attribute so that a shop with a locale prefix in its URLs still works. It renders with textContent, never innerHTML with review text, because reviews are written by strangers.
extensions/review-block/assets/reviews.js:
// Runs on the product page. Talks to the app only through the app proxy
// (/apps/reviews/...), which Shopify forwards to the app with a signature.
(function () {
document.querySelectorAll('[data-reviewmini]').forEach(init);
function init(root) {
const endpoint = `${root.dataset.endpoint}/products/${root.dataset.productId}`;
const list = root.querySelector('[data-reviewmini-list]');
const form = root.querySelector('[data-reviewmini-form]');
const status = root.querySelector('[data-reviewmini-status]');
load();
form?.addEventListener('submit', async (event) => {
event.preventDefault();
status.textContent = '';
const data = Object.fromEntries(new FormData(form));
data.rating = Number(data.rating);
data.product_title = root.dataset.productTitle;
const response = await fetch(`${endpoint}/reviews`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) {
status.textContent = form.dataset.error || 'Sorry, that did not go through. Check the fields and try again.';
return;
}
const review = await response.json();
status.textContent = review.status === 'approved'
? 'Thanks! Your review is published.'
: 'Thanks! Your review will appear once the shop approves it.';
form.reset();
if (review.status === 'approved') load();
});
async function load() {
const response = await fetch(endpoint, { headers: { Accept: 'application/json' } });
if (!response.ok) return;
const { reviews } = await response.json();
list.replaceChildren(...reviews.map(render));
}
function render(review) {
const item = document.createElement('li');
item.className = 'reviewmini__review';
item.innerHTML = `
<span class="reviewmini__stars">${'★'.repeat(review.rating)}${'☆'.repeat(5 - review.rating)}</span>
${review.title ? `<h4></h4>` : ''}
<p></p>
<p class="reviewmini__meta"></p>`;
if (review.title) item.querySelector('h4').textContent = review.title;
item.querySelector('p').textContent = review.body;
item.querySelector('.reviewmini__meta').textContent = `${review.author_name} · ${review.created_at}`;
return item;
}
}
})();
extensions/review-block/assets/reviews.css:
.reviewmini { margin-block: 2rem; max-width: 40rem; }
.reviewmini__heading { margin-block-end: 0.5rem; }
.reviewmini__summary { margin-block-end: 1.5rem; }
.reviewmini__stars { letter-spacing: 0.1em; margin-inline-end: 0.5rem; }
.reviewmini__list { list-style: none; padding: 0; margin: 0 0 2rem; display: grid; gap: 1.25rem; }
.reviewmini__review { border-block-end: 1px solid rgba(0, 0, 0, 0.1); padding-block-end: 1.25rem; }
.reviewmini__review h4 { margin: 0.25rem 0; }
.reviewmini__review p { margin: 0.25rem 0; }
.reviewmini__meta { font-size: 0.875em; opacity: 0.7; }
.reviewmini__form { display: grid; gap: 0.75rem; }
.reviewmini__form label { display: grid; gap: 0.25rem; }
.reviewmini__form input, .reviewmini__form select, .reviewmini__form textarea { font: inherit; padding: 0.5rem; }
.reviewmini__status:empty { display: none; }
Deploy. The CLI runs Theme Check on the extension first, and that caught something on the first attempt, listed at the end.
shopify app deploy --message "Part 6: app proxy and the storefront review block"
│ New version released to users. │
│ reviewmini-4 │
Running with a theme extension
shopify app dev behaves differently once the project has a theme extension. It needs the storefront password of the dev store, because it previews the block on the storefront, and it prompts for it; in a terminal that cannot prompt, set SHOPIFY_FLAG_STORE_PASSWORD in the environment. It also uploads a development theme of its own to the store, the "host theme", for previewing the extension, and prints two extra links.
SHOPIFY_FLAG_STORE_PASSWORD=… shopify app dev --store saanjh-living.myshopify.com --tunnel-url https://reviewmini.shipbytes.dev:3000
Configuring host theme for theme app extension ...
│ The theme app extension development server is ready.
│ 2. Setup your theme app extension in the host theme [2]
│ 3. Preview your theme app extension at http://127.0.0.1:9293 [3]
✅ Ready, watching for changes in your app
│ Using URL: https://reviewmini.shipbytes.dev/storefront
│ Any changes to prefix and subpath will only apply to new installs
That last line is a Shopify rule worth knowing before choosing the proxy path: prefix and subpath are fixed for a shop at install time.
Adding the block to a theme
The host theme is for development. A merchant adds the block to their own theme in the theme editor, and so should you, on a copy. For the series, the store's Horizon theme had an update waiting; the admin's update flow creates an updated copy in the drafts, which leaves the live theme untouched and gives a copy to work on in one step.
In the editor for the copy, open a product page, Add section, the Apps tab, and the app's "Product reviews" block is listed under ReviewMini. Adding it places a section with the block in it; its settings panel shows the product (autofilled), the heading and the form toggle. Save.
The preview in the editor already shows the block with "4.5 out of 5 · 2 reviews", from the metafields, and the two reviews from part 3, from the proxy. Opening the product page on the storefront with ?preview_theme_id=<the copy's ID> shows the same page without the editor around it.
The loop, end to end
On that product page: name "Priya", a title, a review, submit.
Thanks! Your review will appear once the shop approves it.
The CLI's log has the two proxy requests, the list on page load and the POST:
[web] 2026-10-23 17:42:33 /storefront/products/15918744600945 .. ~ 0.10ms
[web] 2026-10-23 17:42:48 /storefront/products/15918744600945/reviews .. ~ 0.07ms
In the admin, the review is in the table as pending. Approve it. The queue worker runs the job from part 3, and the product's metafields in Shopify now read rating_average 4.67, rating_count 3. Reload the product page: "4.7 out of 5 · 3 reviews", and Priya's review at the top.
Every piece of the series ran in that loop: the proxy signature and the settings (part 6 and 3), the ID token and the stored access token (part 2), the moderation endpoint and the admin UI (parts 3 and 4), the job and the metafields (part 3), the Liquid block reading them (part 6). The only thing that did not run was a webhook, and part 5 ran those.
Tests
The proxy tests sign requests the way Shopify does.
tests/Feature/StorefrontTest.php:
<?php
namespace Tests\Feature;
use App\Jobs\SyncProductRating;
use App\Models\Shop;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class StorefrontTest extends TestCase
{
use RefreshDatabase;
private Shop $shop;
protected function setUp(): void
{
parent::setUp();
Queue::fake();
$this->shop = Shop::create(['shop' => 'test-shop']);
$this->shop->forceFill(['access_token' => 'shpat_test', 'installed_at' => now()])->save();
}
/**
* Shopify signs app proxy requests over the query string: parameters sorted by
* name, joined as key=value with no separator, HMAC-SHA256 with the client secret,
* hex encoded. The test signs the same way.
*
* @param array<string, string> $params
*/
private function signed(string $path, array $params = []): string
{
$params += [
'shop' => 'test-shop.myshopify.com',
'timestamp' => (string) time(),
'path_prefix' => '/apps/reviews',
];
ksort($params);
$joined = implode('', array_map(fn ($k, $v) => "{$k}={$v}", array_keys($params), $params));
$params['signature'] = hash_hmac('sha256', $joined, config('shopify.api_secret'));
return $path.'?'.http_build_query($params);
}
public function test_an_unsigned_request_is_rejected(): void
{
$this->getJson('/storefront/products/1?shop=test-shop.myshopify.com')->assertUnauthorized();
}
public function test_only_approved_reviews_are_listed(): void
{
foreach (['approved', 'pending', 'rejected'] as $status) {
$this->shop->reviews()->create([
'product_id' => 'gid://shopify/Product/1', 'product_title' => 'Cushion',
'author_name' => 'Asha', 'rating' => 4, 'body' => $status, 'status' => $status,
]);
}
$this->getJson($this->signed('/storefront/products/1'))
->assertOk()
->assertJsonCount(1, 'reviews')
->assertJsonPath('reviews.0.body', 'approved')
->assertJsonMissingPath('reviews.0.author_email');
}
public function test_a_visitor_review_waits_for_approval_by_default(): void
{
$this->postJson($this->signed('/storefront/products/1/reviews'), [
'author_name' => 'Priya', 'rating' => 5, 'body' => 'Soft and well made', 'product_title' => 'Cushion',
])->assertCreated()->assertJsonPath('status', 'pending');
Queue::assertNothingPushed();
}
public function test_auto_approve_publishes_and_syncs_the_rating(): void
{
$this->shop->settings()->create(['auto_approve' => true]);
$this->postJson($this->signed('/storefront/products/1/reviews'), [
'author_name' => 'Priya', 'rating' => 5, 'body' => 'Soft and well made', 'product_title' => 'Cushion',
])->assertCreated()->assertJsonPath('status', 'approved');
Queue::assertPushed(SyncProductRating::class);
}
}
php artisan test
Tests: 19 passed (65 assertions)
When it goes wrong
LiquidSyntaxError: Expected end_of_string but found pipe from Theme Check on deploy. A filter inside a render tag's arguments: {% render 'stars', rating: rating | round %} is not allowed. Assign the filtered value to a variable first and pass that.
OrphanedSnippet warning on deploy. The snippet is not referenced by any block. A warning only; it goes away once a block renders it.
shopify app dev fails with "Failed to prompt: Enter your store password". The project now has a theme extension and the CLI needs the storefront password. Pass it with --store-password or the SHOPIFY_FLAG_STORE_PASSWORD environment variable.
The block is not in the Apps tab of the theme editor. The extension has not been deployed, or the app is not installed on the store. The host theme that shopify app dev creates shows it before deploy; any other theme needs shopify app deploy.
The block renders but shows no rating, while the admin shows approved reviews. The metafields have not been written for that product, or the definitions were deployed after the values. Approving any review of the product runs the job and writes them.
The proxy answers 401 to every request. The url in [app_proxy] does not match where the app is serving; with the CLI's throwaway tunnel it changes on every start and the proxy only follows after a deploy or a reinstall. A fixed hostname avoids this. Also check the clock: the signature's timestamp must be within 90 seconds.
The proxy answers 404 "App not installed". The app was uninstalled from the shop. Part 5's install URL puts it back.
The form posts and nothing happens. Open the browser's network panel; a 422 means validation failed, and the body says which field. The script's product_title comes from a data attribute on the block, which has to be there.
Where this leaves the app
ReviewMini is a working embedded app on current Shopify: token exchange with expiring tokens, Polaris 2, Events, app-owned metafields, a theme app extension, and the privacy topics, with nineteen tests and one commit per part at shipbytes/laravel-shopify-app-guide. What it is not is a production deployment: it runs behind a development tunnel on SQLite with a queue:listen in a terminal. The Docker and GitHub Actions series on this site cover that half, and nothing in this app resists them; swap SQLite for MySQL, run the queue worker as a service, and point application_url at the server. The tests here are deliberately thin, one file per surface; the Laravel testing series shows how to grow a suite like this, including signed webhooks, queued jobs and the clock.
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
6 / 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