Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
SDK:
ReviewsServiceTypes: SDK Types
Prerequisites
A client exported from
@/lib/lynkow(Add Lynkow to an Existing Project)Guide 4: Dynamic Forms for the anti-spam fields and
formStartedAt, which work the same way here
List reviews
reviews.list() returns approved reviews only.
import { lynkow } from '@/lib/lynkow'
const { data: reviews, meta } = await lynkow.reviews.list({
page: 1,
limit: 10, // 20 by default, 100 at most
sort: 'created_at', // or 'rating', 'review_date', 'author_name', 'display_order'
order: 'desc',
minRating: 4, // 1 to 5, inclusive; maxRating works the same way
})
reviews[0].authorName // string
reviews[0].rating // 1 to 5
reviews[0].content // string, or null on an imported review without text
meta.lastPage // pagination: total, perPage, currentPage, lastPage
meta.averageRating // average of the approved reviews, 0 when there are none
meta.totalApproved // their countmeta.averageRating and meta.totalApproved ignore the rating range and product: they describe all the approved reviews in the languages the request serves. meta.total counts the reviews matching every filter. To show one review, lynkow.reviews.getBySlug() takes its slug or id.
A review card
// components/review-card.tsx
import type { Review } from 'lynkow'
export function ReviewCard({ review }: { review: Review }) {
return (
<article lang={review.locale}>
<p aria-label={`${review.rating} out of 5 stars`}>
{'★'.repeat(review.rating)}{'☆'.repeat(5 - review.rating)}
</p>
{review.title && <h3>{review.title}</h3>}
{review.content && <p>{review.content}</p>}
<footer>
<strong>{review.authorName}</strong>{' '}
<time dateTime={review.createdAt}>{new Date(review.createdAt).toLocaleDateString()}</time>
</footer>
</article>
)
}A paginated list with its summary
// components/review-list.tsx
import Link from 'next/link'
import { lynkow } from '@/lib/lynkow'
import { ReviewCard } from './review-card'
export async function ReviewList({ page = 1, minRating }: { page?: number; minRating?: number }) {
const { data: reviews, meta } = await lynkow.reviews.list({
page,
limit: 10,
minRating,
sort: 'created_at',
order: 'desc',
})
return (
<section>
<p>
{meta.averageRating.toFixed(1)} / 5 from {meta.totalApproved} reviews
</p>
{reviews.length === 0 && <p>No reviews yet.</p>}
{reviews.map((review) => (
<ReviewCard key={review.id} review={review} />
))}
{meta.lastPage > 1 && (
<nav aria-label="Review pages">
{page > 1 && <Link href={`?page=${page - 1}`}>Previous</Link>}
<span>Page {meta.currentPage} of {meta.lastPage}</span>
{page < meta.lastPage && <Link href={`?page=${page + 1}`}>Next</Link>}
</nav>
)}
</section>
)
}// app/reviews/page.tsx
import { ReviewList } from '@/components/review-list'
import { ReviewForm } from '@/components/review-form'
export default async function ReviewsPage({
searchParams,
}: {
searchParams: Promise<{ page?: string; rating?: string }>
}) {
const params = await searchParams
return (
<main>
<h1>Customer Reviews</h1>
<ReviewList
page={Number(params.page) || 1}
minRating={params.rating ? Number(params.rating) : undefined}
/>
<ReviewForm />
</main>
)
}For a single rating, pass the same value as minRating and maxRating.
Submit a review
Read the settings first: they say whether to render the form at all.
const settings = await lynkow.reviews.settings()
settings.publicSubmissionEnabled // false: render no form, a submission answers 403
settings.requireEmail // true: authorEmail is required
settings.customFieldsSchema // extra questions ({ id, label, type, required, options }), [] when noneauthorName (2 to 100 characters), rating (1 to 5) and content (10 to 5000 characters) are always required. title (up to 200 characters) is optional. Answers to the extra questions go in customFields, keyed by their id.
const result = await lynkow.reviews.submit(
{
authorName: 'Alice',
rating: 5,
content: 'Excellent product, highly recommend.',
authorEmail: '[email protected]',
},
{ formStartedAt } // Date.now() taken when the form was shown
)
// { id: string, status: 'approved' | 'pending', message: string }status tells you whether the review is live: 'approved' when it met the site's auto-approval rule, 'pending' when it waits for moderation. Nothing in the settings predicts it. message is ready to display. The SDK sends the client's locale as the review's language and clears its cached review lists after a successful submit.
A review form
// components/review-form.tsx
'use client'
import { useEffect, useRef, useState } from 'react'
import { isLynkowError, type ReviewSettings, type ReviewSubmitResponse } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
export function ReviewForm() {
const [settings, setSettings] = useState<ReviewSettings | null>(null)
const [result, setResult] = useState<ReviewSubmitResponse | null>(null)
const [errors, setErrors] = useState<Record<string, string>>({})
const [globalError, setGlobalError] = useState<string | null>(null)
const startedAt = useRef(Date.now())
useEffect(() => {
lynkow.reviews.settings().then(setSettings)
}, [])
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
const form = new FormData(e.currentTarget)
const text = (name: string) => (form.get(name) as string | null) || undefined
setErrors({})
setGlobalError(null)
try {
setResult(
await lynkow.reviews.submit(
{
authorName: text('authorName') ?? '',
authorEmail: text('authorEmail'),
title: text('title'),
content: text('content') ?? '',
rating: Number(form.get('rating')),
},
{ formStartedAt: startedAt.current }
)
)
} catch (error) {
if (isLynkowError(error) && error.code === 'VALIDATION_ERROR') {
const fieldErrors: Record<string, string> = {}
for (const d of error.details ?? []) if (d.field) fieldErrors[d.field] = d.message
setErrors(fieldErrors)
} else {
setGlobalError(isLynkowError(error) ? error.message : 'Something went wrong.')
}
}
}
if (!settings?.publicSubmissionEnabled) return null
if (result) return <p role="status">{result.message}</p>
return (
<form onSubmit={handleSubmit}>
<fieldset>
<legend>Your rating *</legend>
{[5, 4, 3, 2, 1].map((n) => (
<label key={n}>
<input type="radio" name="rating" value={n} required defaultChecked={n === 5} /> {n}
</label>
))}
</fieldset>
<input name="authorName" placeholder="Your name *" required minLength={2} maxLength={100} />
<input
name="authorEmail"
type="email"
placeholder={settings.requireEmail ? 'Email *' : 'Email (optional)'}
required={settings.requireEmail}
/>
<input name="title" placeholder="Title (optional)" maxLength={200} />
<textarea name="content" placeholder="Your review *" required minLength={10} maxLength={5000} />
{Object.entries(errors).map(([field, message]) => (
<p key={field} role="alert">{message}</p>
))}
{globalError && <p role="alert">{globalError}</p>}
<button type="submit">Submit review</button>
</form>
)
}Errors
|
| Cause |
|---|---|---|
| per field in | A field breaks a rule above, or |
|
| Public submissions are off |
|
|
|
|
| Missing or rejected token |
|
|
|
Guide 12 covers LynkowError in general.
reCAPTCHA
Reviews follow the site's spam settings only. When the site uses reCAPTCHA, mint the token as Guide 4 shows, with the action review_submit, and pass it as recaptchaToken:
await lynkow.reviews.submit(reviewData, { recaptchaToken, formStartedAt })Reviews in several languages
Every review carries locale, the language it is written in. On a multi-language site:
With a request locale (the
localeoption or the client's locale), every review appears once, in that locale when translated, otherwise in another language withisFallback: true(fallback contract).fallback: falsekeeps only the reviews in the requested locale.With
productand no request locale, the product's reviews come back in every language.With neither, the list holds the reviews of the site's default locale.
The language filter hides every review not served in that language, without changing which translation is served:
const { data: french } = await lynkow.reviews.list({ language: 'fr', limit: 10 })An unknown language code returns an empty list. On a single-language site no locale filter applies.
Reviews on a product page
On a site with a product catalog (Guide 18), pass productId to submit() to link a review to a product, and product to list() to read a product's reviews. Both take the product's prod_... id or its slug.
// components/product-reviews.tsx
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
import { ReviewCard } from './review-card'
export async function ProductReviews({ productId }: { productId: string }) {
try {
const { data: reviews, meta } = await lynkow.reviews.list({ product: productId, limit: 10 })
return (
<section>
<h2>{meta.total} reviews</h2>
{reviews.map((review) => <ReviewCard key={review.id} review={review} />)}
</section>
)
} catch (error) {
// The product is not published on the storefront
if (isLynkowError(error) && error.code === 'NOT_FOUND') return null
throw error
}
}await lynkow.reviews.submit({ ...reviewData, productId }, { formStartedAt })Only a product published on the storefront can be linked. Any other value fails with
VALIDATION_ERRORand adetailsentry onproductId, and nothing is stored.list({ product })throwsNOT_FOUNDfor a product the storefront does not serve, and returns an emptydatafor a published product without reviews.For a product, use
meta.total:meta.averageRatingandmeta.totalApprovedstay site-wide.review.productIdis the linked product'sprod_...id, ornullwhen none is linked or the product is no longer published.lynkow.products.getBySlug()accepts that id.
The approved reviews linked to a product also feed the aggregateRating of its JSON-LD graph, which products.getBySlug() returns (Guide 16). Search engines show that rating only when the reviews are visible on the product page, so list them there.
Cache
With a client created with cache: true, reviews.list() and reviews.getBySlug() are kept in memory for 5 minutes and reviews.settings() for 10 minutes; lynkow.reviews.clearCache() empties them. Without cache: true only your framework's cache applies. Guide 11 shows how to revalidate pages when a review event arrives.
Next Steps
Guide 6: Multi-language (i18n) - locales and the fallback contract
Guide 18: Product Catalog - the product pages reviews link to