Quick summary
- Reduce CLS by using Next.js font optimization and proper font-display.
- Configure next/image for remote CDNs and optimize product images for ecommerce.
- Use i18n routing, hreflang, and translated meta for multilingual SEO.
- Keep secrets out of the client, use HTTP-only cookies for auth, and prefer edge-safe Middleware.
- Choose Server Actions or Route Handlers based on complexity; prefer direct-to-storage uploads for files.
- For headless Shopify, combine SSG/SSR, canonical tags, structured data, and image optimizations.
Overview
This post collects practical solutions to advanced Next.js questions you’ll face as projects scale. Topics include performance (fonts/images), SEO for ecommerce, internationalization, security (env vars and auth), file uploads, Middleware guidance, and approaches for headless Shopify builds. Each section gives focused guidance you can apply quickly.
Fonts: reduce CLS and improve load
Why CLS happens: late-loading custom fonts cause layout shifts when the fallback text is replaced.
How to address it:
- Use Next.js built-in font utilities (next/font) to load fonts locally or from Google Fonts.
- Preload critical fonts so the browser fetches them early.
- Use font-display: swap to show fallbacks until the custom font is ready.
- Prefer subsets (latin, latin-ext) for lower payloads.
- Consider variable fonts when appropriate for fewer files.
Result: fewer layout shifts and faster perceived rendering.
Remote images with next/image
To serve images from Shopify, Cloudinary, or other CDNs:
- Whitelist domains in next.config.js via images.domains or use images.remotePatterns for complex patterns.
- Example entries include your Shopify CDN host and any third-party image services.
Benefits:
- next/image will handle automatic resizing, format negotiation (WebP/AVIF when available), and optimization.
- Keep CDN and cache headers configured for long-lived caching where appropriate.
Ecommerce image optimization
Product pages are image-heavy; optimize with these rules:
- Always set width and height (or use layout options) to avoid layout shifts.
- Mark above-the-fold images with priority.
- Use responsive sizes and srcset via next/image.
- Serve modern formats (WebP/AVIF) while falling back to JPEG/PNG for older browsers.
- Compress at source when possible (Cloudinary/Shopify transformations).
- Lazy-load non-critical images.
These steps reduce page weight, speed render time, and help conversions.
i18n routing in the App Router
Next.js supports locale-aware routing through next.config.js i18n settings. With the App Router:
- Define locales and defaultLocale.
- Next.js generates locale-prefixed routes (e.g., /en/, /hi/).
- Implement language switchers that update routes, not just UI strings.
SEO tips:
- Add hreflang tags to pages to signal language/region versions to search engines.
- Ensure your sitemap lists all localized URLs.
- Translate meta tags and structured data for each locale.
Securing environment variables and secrets
Keep secrets out of your repository:
- Use .env.local for local development and never commit it.
- Only prefix variables with NEXT_PUBLIC_ when they must be exposed to the browser.
- Store API keys, DB credentials, and other secrets without NEXT_PUBLIC_ so they remain server-only.
- Use your host’s environment variable UI (Vercel, Netlify, etc.) for production values.
- Rotate keys periodically and limit scope/permissions.
Authentication: cookies vs tokens
Best practices:
- Prefer HTTP-only cookies to store session tokens to mitigate XSS exposure.
- If using JWTs, store them in HTTP-only cookies rather than localStorage.
- Use secure, SameSite, and proper expiration settings on cookies.
- Consider NextAuth.js or a similar library for standard flows (OAuth, email, credentials).
- Use refresh tokens and short-lived access tokens for better control.
Balance security and UX: choose approaches that fit your threat model and scale.
When to use Middleware
Good use cases:
- Lightweight auth checks and redirects.
- Locale detection and routing.
- A/B tests or header-based experiments.
What to avoid:
- Heavy CPU tasks, long-running database calls, or complex business logic. Middleware runs at the edge and needs to be fast.
Pattern: keep Middleware thin and push heavy operations to server functions or external services.
Server Actions vs Route Handlers
Pick based on needs:
- Server Actions: convenient for simple forms and mutations tightly coupled to UI. They let you keep logic closer to components.
- Route Handlers (API routes): preferred for complex APIs, heavy integrations, or when a clear backend contract is needed.
Guideline: use Server Actions for simple CRUD tied directly to UI; use Route Handlers for third-party APIs, complex validation, or when multiple clients will consume the endpoint.
Handling file uploads
Recommended approaches:
- Direct-to-storage: have the client upload directly to S3, R2, or Cloudinary using signed URLs or SDKs. This reduces server load and improves reliability.
- Server-mediated: accept files via a Route Handler if you need server-side validation or processing before storage.
- Always validate file type, size, and use virus-scanning where necessary.
- Provide progress feedback on the client for better UX.
Building a headless Shopify store without SEO regressions
Key practices:
- Use SSG or SSR for product and category pages so content is crawlable and fast.
- Emit correct canonical URLs and meta tags for all pages.
- Attach structured product data (JSON-LD) for rich search results.
- Optimize product images and feeds.
- Generate an XML sitemap covering all storefront URLs.
Combining these keeps your headless store fast and search-friendly.
Conclusion
This FAQ covers practical, high-impact steps for advanced Next.js projects: performance optimizations, secure patterns, i18n and SEO, file uploads, and headless ecommerce. Apply these patterns incrementally — start with fonts and images, then secure secrets and authentication, and finally refine routing and uploads.
Want help implementing any of these items or building a headless Shopify site with Next.js? Reach out and mention which area you want to prioritize.
Home: Home: https://prateeksha.com
Blog: Blog: https://prateeksha.com/blog
Canonical: Canonical: https://prateeksha.com/blog/nextjs-faqs-beginner-to-advanced-part-5

Top comments (0)