Kritim Yantra
Aug 30, 2025
Remember the first PHP site you deployed? You were so proud! It worked on your local machine, you FTP'd the files up to some shared hosting, and... it was alive on the internet! 🎉
But then you visited it on your phone. The page loaded... slowly. It felt a little clunky. Every time you clicked a link, the whole page had to refresh. You wanted to add those slick, modern animations you see on other websites, but mixing jQuery with your PHP felt like trying to fit a square peg in a round hole.
What if I told you you don't have to throw away your battle-tested PHP backend? What if you could keep all that logic but give your users a blazing-fast, modern, app-like experience?
That's exactly what we're doing today. We're combining the robust backend power of PHP with the slick, dynamic frontend magic of Next.js. Trust me, it's easier than you think.
Think of it like this: your PHP is the engine of your car—reliable, powerful, and doing all the hard work under the hood. Next.js is the gorgeous body, the smooth steering, and the interactive dashboard that makes driving a joy.
The result? A website that feels instantly fast, is more engaging, and is a delight to maintain.
Let's build a simple but practical application: a "Quote of the Day" website.
Ready? Let's go.
We'll keep this simple and modern. No complex frameworks needed for this example.
Step 1: Create your project folder
Create a new directory for your project and inside it, a folder for the PHP API.
mkdir php-nextjs-tutorial
cd php-nextjs-tutorial
mkdir php-api
cd php-api
Step 2: Create the quotes endpoint
Using your favorite code editor, create a file named api.php
inside the php-api
folder.
<?php
// php-api/api.php
header('Access-Control-Allow-Origin: http://localhost:3000'); // Allows our Next.js dev server to talk to it
header('Content-Type: application/json');
// A simple array of quotes
$quotes = [
"The greatest glory in living lies not in never falling, but in rising every time we fall. - Nelson Mandela",
"The way to get started is to quit talking and begin doing. - Walt Disney",
"Your time is limited, so don't waste it living someone else's life. - Steve Jobs",
"If life were predictable it would cease to be life, and be without flavor. - Eleanor Roosevelt",
"If you look at what you have in life, you'll always have more. - Oprah Winfrey"
];
// Pick a random quote
$randomQuote = $quotes[array_rand($quotes)];
// Output it as JSON
echo json_encode([
'quote' => $randomQuote,
'author' => 'Famous Person'
]);
→ What we just did: We created a simple PHP script that outputs a random quote in JSON format. The header
function is crucial here to avoid CORS errors when our frontend tries to connect.
Step 3: Test your API
You need to serve this PHP file. If you have a local server like XAMPP/MAMP, place the php-api
folder in your htdocs
directory and visit http://localhost/php-api/api.php
.
Pro Tip: No local PHP setup? You can run a quick server from the terminal right in the php-api
directory using PHP's built-in server:
php -S localhost:8000
Then visit http://localhost:8000/api.php
. You should see a random quote in JSON! ✅
Now, let's create the part the user actually sees.
Step 1: Create a new Next.js app
Open a new terminal window, navigate outside your php-api
folder, and run:
npx create-next-app@latest quote-frontend
cd quote-frontend
npm run dev
Your new Next.js site is now running at http://localhost:3000
. Amazing!
Step 2: Create a page to fetch and display the quote
Edit the file app/page.js
in your quote-frontend
directory.
// quote-frontend/app/page.js
'use client'; // This is needed because we're using React hooks
import { useState, useEffect } from 'react';
export default function Home() {
const [quote, setQuote] = useState({ text: '', author: '' });
const [isLoading, setIsLoading] = useState(true);
const fetchQuote = async () => {
setIsLoading(true);
try {
// This URL points to your local PHP API!
const response = await fetch('http://localhost:8000/api.php');
const data = await response.json();
setQuote({ text: data.quote, author: data.author });
} catch (error) {
console.error("Oops! Couldn't fetch the quote.", error);
setQuote({ text: "Failed to load quote.", author: "" });
}
setIsLoading(false);
};
// Fetch a quote when the page loads
useEffect(() => {
fetchQuote();
}, []);
return (
<main style={{ padding: '2rem', textAlign: 'center' }}>
<h1>Inspirational Quote of the Day</h1>
{isLoading ? (
<p>Loading your inspiration...</p>
) : (
<>
<blockquote style={{ fontSize: '1.5em', margin: '2em' }}>
"{quote.text}"
</blockquote>
<p><strong>- {quote.author}</strong></p>
</>
)}
<br />
<button
onClick={fetchQuote}
style={{ padding: '10px 20px', fontSize: '1em', cursor: 'pointer' }}
>
Give Me Another Quote!
</button>
</main>
);
}
→ What we just did: We built a React component that:
useEffect
), calls the fetchQuote
function.fetchQuote
calls our PHP API endpoint.setQuote
).http://localhost:8000
.http://localhost:3000
.http://localhost:3000
.You should see your beautifully styled Next.js page displaying a random quote from your PHP backend! Click the button—the quote changes instantly. This is the power of a decoupled architecture!
Q: Can I use a PHP framework like Laravel or Symfony with this?
A: Absolutely! And you should for bigger projects. Just create API endpoints (e.g., /api/quotes
) in your framework instead of a simple api.php
file. The principle is identical.
Q: What about security? Isn't allowing CORS a bad idea?
A: Great point. In production, you must lock this down. Instead of header('Access-Control-Allow-Origin: http://localhost:3000');
, you would set it to your actual production domain (e.g., https://myawesomeapp.com
).
Q: How do I deploy this to a real server?
A: You deploy them separately!
localhost:8000
to your live API's URL (e.g., https://api.myawesomeapp.com
).See? You don't have to choose. You can have the best of both worlds: the maturity of PHP and the modern developer experience of Next.js.
I learned this approach the hard way after struggling with clunky, full-page-refresh apps for years. This changed everything for me.
Now I'd love to hear from you: What's the first project you'd rebuild or enhance using this PHP + Next.js combo? A personal blog? An admin dashboard? Tell me about it in the comments below! 👇
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google