
Why I Use Laravel as a Backend and Next.js as a Frontend
MA
Mohammad Ali Khan
Why I split my portfolio into a Laravel backend and a Next.js frontend, how the two talk through a versioned REST API, and how tag-based caching with on-demand revalidation keeps the site fast while admin edits go live almost instantly.
When I rebuilt my portfolio, I had a choice to make. I could build everything inside Laravel with Blade templates, or I could split the project into two parts: a Laravel backend and a Next.js frontend. I chose the split. This post explains why, how the two parts talk to each other, and what I learned along the way.
## The Idea: A Headless Setup
In a traditional Laravel app, the same codebase handles the database, the business logic and the HTML. In a headless setup, those jobs are split:
- **Laravel** handles data, the admin panel, validation, authentication and a versioned REST API.
- **Next.js** fetches that data and renders a fast, SEO-friendly public website.
Each side does what it is best at.
## Why Laravel for the Backend
Laravel is still one of the most productive backend frameworks I know:
- **Eloquent ORM** makes relationships like projects, categories, tags and blog posts easy to model.
- **Form Requests** keep validation clean and in one place.
- **A mature ecosystem**: queues, mail, rate limiting, testing and file storage all come built in.
- **An admin panel in the same app**: I manage all my content from a Laravel dashboard, and the public site never needs direct database access.
My API is versioned under `/api/v1/`, so the frontend can rely on a stable contract:
```
# GET /api/v1/profile
# GET /api/v1/projects?category=full-stack-applications
# GET /api/v1/blog-posts?search=laravel&per_page=10
# POST /api/v1/contact
```
Every response follows the same shape, which keeps the frontend code simple:
# ```json
{
"success": true,
"data": [...],
"message": "Resource retrieved successfully",
"meta": { "total": 10 }
}
```
## Why Next.js for the Frontend
A portfolio has to be fast and easy for search engines to find. Next.js gives me both:
- **Server-side rendering and static generation**, so pages arrive as ready HTML that search engines can crawl easily.
- **Built-in data caching**, so I don't call the API on every visit.
- **A modern React developer experience** for building rich, interactive UI.
- **Separate deployment**: the frontend can run on an edge-friendly host while Laravel runs on a regular server.
## How They Talk: Fetching with Cache Tags
On the Next.js side, each API call is cached and labeled with a tag:
# ```js
export async function getProjects() {
const res = await fetch(`${process.env.API_URL}/api/v1/projects`, {
headers: { Accept: 'application/json' },
next: { revalidate: 300, tags: ['projects'] },
});
return (await res.json()).data;
}
```
With `revalidate: 300`, Next.js serves cached data and refreshes it at most every five minutes. That keeps the site fast and takes load off Laravel.
## The Real Problem: Stale Content
Caching creates a new problem. If I fix a typo in a blog post from the admin panel, I don't want to wait five minutes to see it live.
The fix is **on-demand revalidation**. When content changes in Laravel, Laravel tells Next.js exactly which cache tags to clear.
On the Laravel side, I map each model to the frontend tags it affects:
# ```php
public const MODEL_TAGS = [
Project::class => ['projects'],
BlogPost::class => ['blog-posts'],
Category::class => ['categories', 'projects', 'blog-posts'],
Setting::class => ['settings', 'profile'],
];
```
When a model is saved, its tags are collected and sent in **one** request, **after** the response has already gone back to the admin user. I do this with Laravel's `defer()` helper:
# ```php
defer(fn () => $this->flush());
```
The call is protected with a shared secret header and a short timeout:
# ```php
Http::timeout(5)
->withHeaders(['x-revalidate-secret' => config('services.frontend.revalidate_secret')])
->post($frontendUrl . '/api/revalidate', ['tags' => $tags]);
```
On the Next.js side, a small route handler checks the secret and clears the tags:
# ```js
import { revalidateTag } from 'next/cache';
export async function POST(request) {
if (request.headers.get('x-revalidate-secret') !== process.env.REVALIDATE_SECRET) {
return Response.json({ ok: false }, { status: 401 });
}
const { tags } = await request.json();
tags.forEach((tag) => revalidateTag(tag));
return Response.json({ ok: true });
}
```
Edits now show up on the live site almost instantly. And if the frontend is unreachable for a moment, nothing breaks: the save still succeeds, the failure is logged, and the cache refreshes on its own within five minutes.
## Security Considerations
Splitting the app means the API is public, so I treat it carefully:
- **Rate limiting** of 60 requests per minute protects the API from abuse.
- **Filtered settings**: sensitive values such as mail credentials never leave the backend. Only public settings are returned.
- **Validation at the edge**: the contact and newsletter endpoints validate every input with Form Requests and return proper `422` responses.
- **Secret-protected revalidation**: only Laravel can clear the frontend cache.
## Testing the API
Because the frontend depends completely on the API, I test the API thoroughly. Each endpoint has feature tests backed by model factories, and I keep a Postman collection for manual checks. When the API contract is tested, I can change the frontend with confidence.
## When This Setup Makes Sense (and When It Doesn't)
**Choose Laravel + Next.js when:**
- SEO and page speed matter.
- You want a rich, interactive UI.
- You may add other clients later, such as a mobile app, using the same API.
**Stick with plain Laravel + Blade when:**
- The project is small or mostly an internal tool.
- You want a single deployment and the simplest possible setup.
Two apps mean two deployments, two sets of environment variables and an API contract to maintain. That cost is worth it only if you need the benefits.
## Final Thoughts
Laravel and Next.js complement each other well. Laravel gives me a solid, testable backend and a comfortable admin experience. Next.js gives visitors a fast, modern website. With tag-based caching and on-demand revalidation, I get the speed of a cached site without giving up instant updates.
If you're planning a project with this stack, or want help building one, feel free to [get in touch](/contact).
Tags:#Laravel#Next.js#REST API#Headless Architecture#Web Development