A production-ready full-stack starter template with Laravel backend, Next.js frontend, MySQL database, and complete authentication system
StarterCode-Full-Stack-Laravel-NextJS is a modern, scalable boilerplate that provides a complete foundation for building full-stack web applications. This template comes with a pre-configured authentication system, database setup, API infrastructure, and a responsive frontend ready for immediate development.
What's Included:
- Complete authentication system (registration, login, logout, password reset)
- RESTful API with Laravel backend
- Modern React-based frontend with Next.js
- MySQL database with migrations
- CORS configuration for seamless frontend-backend communication
- TypeScript support for type-safe development
Perfect for:
- SaaS applications
- E-commerce platforms
- Admin dashboards
- API-driven web apps
- Rapid prototyping with authentication
- Next.js 14+ - React framework with server-side rendering
- TypeScript - Type-safe JavaScript
- Tailwind CSS - Utility-first CSS framework
- React Hooks - Modern state management
- Laravel 11 - PHP framework for web applications
- Laravel Sanctum - API authentication system
- RESTful API - Standardized API endpoints
- Eloquent ORM - Database query builder
- MySQL 8.0+ - Relational database
- Migrations - Version-controlled database schema
- Seeders - Sample data generation
- User registration with email verification
- Secure login/logout functionality
- Password reset via email
- Token-based API authentication (Laravel Sanctum)
- Protected routes on frontend and backend
- Session management
- CSRF protection
- Pre-built authentication pages (login, register, forgot password)
- Protected dashboard layout
- API integration utilities
- Form validation
- Error handling
- Responsive design
- Loading states and feedback
- Authentication API endpoints
- User management
- Role-based access control ready
- Request validation
- Error handling middleware
- CORS configured for frontend
- API rate limiting
- Secure password hashing
- User table with authentication fields
- Password reset tokens table
- Migration files for easy setup
- Seeder for test users
- Foreign key relationships configured
Before you begin, ensure you have the following installed:
- PHP 8.1 or higher
- Composer 2.x
- Node.js 18.x or higher
- MySQL 8.0 or higher
- npm or yarn
- Git
git clone https://github.com/NishulDhakar/StarterCode-Laravel-NextJS.git
cd StarterCode-Laravel-NextJScd backendcomposer installCopy the example environment file:
cp .env.example .envOpen the .env file and configure your database connection:
APP_NAME=StarterCode
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_nextjs_db
DB_USERNAME=root
DB_PASSWORD=your_password
# Frontend URL for CORS
FRONTEND_URL=http://localhost:3000
SANCTUM_STATEFUL_DOMAINS=localhost:3000
# Mail Configuration (for password reset emails)
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@startercode.com
MAIL_FROM_NAME="${APP_NAME}"Create a new MySQL database:
mysql -u root -pCREATE DATABASE laravel_nextjs_db;
EXIT;php artisan key:generateThis will create all necessary tables including users, password_resets, and personal_access_tokens:
php artisan migrateCreate a test user for development:
php artisan db:seedThis creates a default user:
- Email: test@example.com
- Password: password
php artisan serveBackend API running at: http://localhost:8000
Test the API:
curl http://localhost:8000/api/healthOpen a new terminal window:
cd frontendnpm install
# or
yarn installCreate environment file:
cp .env.example .env.localUpdate .env.local:
NEXT_PUBLIC_API_URL=http://localhost:8000/api
NEXT_PUBLIC_APP_NAME=StarterCodenpm run dev
# or
yarn devFrontend application running at: http://localhost:3000
Your application is now fully configured with authentication! You can:
- Register a new account: Visit
http://localhost:3000/register - Login: Visit
http://localhost:3000/login - Access protected dashboard: Visit
http://localhost:3000/dashboard(requires login) - Test API authentication: Use the provided API endpoints
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| POST | /api/register |
Register new user | No |
| POST | /api/login |
User login | No |
| POST | /api/logout |
User logout | Yes |
| GET | /api/user |
Get authenticated user | Yes |
| POST | /api/forgot-password |
Request password reset | No |
| POST | /api/reset-password |
Reset password | No |
Register User:
curl -X POST http://localhost:8000/api/register \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"password_confirmation": "password123"
}'Login:
curl -X POST http://localhost:8000/api/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'Get Authenticated User:
curl -X GET http://localhost:8000/api/user \
-H "Authorization: Bearer YOUR_TOKEN_HERE"StarterCode-Laravel-NextJS/
│
├── backend/ # Laravel Backend
│ ├── app/
│ │ ├── Http/
│ │ │ ├── Controllers/
│ │ │ │ └── Auth/ # Authentication controllers
│ │ │ └── Middleware/
│ │ │ └── Authenticate.php # Auth middleware
│ │ ├── Models/
│ │ │ └── User.php # User model
│ │ └── Providers/
│ ├── routes/
│ │ ├── api.php # API routes with auth
│ │ └── web.php
│ ├── database/
│ │ ├── migrations/
│ │ │ ├── create_users_table.php
│ │ │ ├── create_password_resets_table.php
│ │ │ └── create_personal_access_tokens_table.php
│ │ └── seeders/
│ │ └── UserSeeder.php # Test user seeder
│ ├── config/
│ │ ├── auth.php # Auth configuration
│ │ ├── sanctum.php # API auth config
│ │ └── cors.php # CORS settings
│ └── .env.example
│
├── frontend/ # Next.js Frontend
│ ├── src/
│ │ ├── app/
│ │ │ ├── (auth)/ # Auth pages group
│ │ │ │ ├── login/
│ │ │ │ ├── register/
│ │ │ │ └── forgot-password/
│ │ │ ├── (protected)/ # Protected pages group
│ │ │ │ └── dashboard/
│ │ │ └── layout.tsx
│ │ ├── components/
│ │ │ ├── auth/ # Auth components
│ │ │ └── ui/ # UI components
│ │ ├── lib/
│ │ │ ├── api.ts # API utilities
│ │ │ └── auth.ts # Auth helpers
│ │ ├── hooks/
│ │ │ └── useAuth.ts # Auth hook
│ │ └── middleware.ts # Route protection
│ └── .env.example
│
└── README.md
| Column | Type | Description |
|---|---|---|
| id | BIGINT | Primary key |
| name | VARCHAR | User's full name |
| VARCHAR | Unique email address | |
| email_verified_at | TIMESTAMP | Email verification timestamp |
| password | VARCHAR | Hashed password |
| remember_token | VARCHAR | Remember me token |
| created_at | TIMESTAMP | Creation timestamp |
| updated_at | TIMESTAMP | Last update timestamp |
| Column | Type | Description |
|---|---|---|
| VARCHAR | User's email | |
| token | VARCHAR | Reset token |
| created_at | TIMESTAMP | Token creation time |
| Column | Type | Description |
|---|---|---|
| id | BIGINT | Primary key |
| tokenable_type | VARCHAR | Model type |
| tokenable_id | BIGINT | Model ID |
| name | VARCHAR | Token name |
| token | VARCHAR | Hashed token |
| abilities | TEXT | Token permissions |
| last_used_at | TIMESTAMP | Last usage time |
| expires_at | TIMESTAMP | Expiration time |
| created_at | TIMESTAMP | Creation timestamp |
| updated_at | TIMESTAMP | Update timestamp |
- User submits registration form on frontend
- Frontend sends POST request to
/api/register - Backend validates input and creates user
- Password is hashed using bcrypt
- User record saved to database
- Authentication token generated
- Token returned to frontend
- User automatically logged in
- User submits login credentials
- Frontend sends POST request to
/api/login - Backend validates credentials
- If valid, authentication token generated
- Token stored in frontend (localStorage/cookies)
- User redirected to dashboard
- Subsequent requests include token in headers
- User attempts to access protected route
- Middleware checks for valid token
- Token validated against database
- If valid, request proceeds
- If invalid, user redirected to login
# Clear all caches
php artisan optimize:clear
# Create new migration
php artisan make:migration create_posts_table
# Create model with migration
php artisan make:model Post -m
# Create controller
php artisan make:controller PostController
# Create seeder
php artisan make:seeder PostSeeder
# Run seeders
php artisan db:seed
# Rollback migrations
php artisan migrate:rollback
# Reset database
php artisan migrate:fresh --seed
# Create new API route
# Edit routes/api.php# Development server
npm run dev
# Production build
npm run build
# Start production server
npm run start
# Lint code
npm run lint
# Type check
npm run type-checkThe backend is configured to accept requests from your frontend. In config/cors.php:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'supports_credentials' => true,API authentication is handled by Laravel Sanctum. Configuration in config/sanctum.php:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost:3000')),
'expiration' => null, // Tokens don't expire
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],Problem: Database connection refused
Solution:
- Verify MySQL is running:
sudo systemctl status mysql - Check database credentials in
.env - Ensure database exists:
SHOW DATABASES;
Problem: 419 CSRF token mismatch
Solution:
- Clear Laravel cache:
php artisan config:clear - Verify CORS settings in
config/cors.php - Check
SANCTUM_STATEFUL_DOMAINSin.env
Problem: Migration errors
Solution:
- Drop all tables and re-migrate:
php artisan migrate:fresh - Check database user permissions
- Verify migration file syntax
Problem: API connection refused
Solution:
- Verify backend is running on
http://localhost:8000 - Check
NEXT_PUBLIC_API_URLin.env.local - Test API endpoint with curl
Problem: Authentication not persisting
Solution:
- Check token storage implementation
- Verify API token is included in request headers
- Check browser console for errors
Problem: CORS errors
Solution:
- Verify
FRONTEND_URLin backend.env - Check CORS configuration in
config/cors.php - Ensure credentials are included in fetch requests
Problem: Access denied for user
Solution:
- Verify MySQL user exists:
SELECT User FROM mysql.user; - Grant permissions:
GRANT ALL PRIVILEGES ON laravel_nextjs_db.* TO 'root'@'localhost'; - Flush privileges:
FLUSH PRIVILEGES;
Backend:
- Set
APP_ENV=productionin.env - Set
APP_DEBUG=falsein.env - Use strong
APP_KEY - Enable HTTPS only
- Configure proper CORS origins
- Set up database backups
- Use environment variables for secrets
- Enable rate limiting on API routes
- Keep Laravel and dependencies updated
Frontend:
- Store tokens securely (httpOnly cookies recommended)
- Implement CSRF protection
- Sanitize user inputs
- Use environment variables for API URLs
- Enable HTTPS
- Implement proper error handling
- Add request/response interceptors
- Set up proper Content Security Policy
Database:
- Use strong passwords
- Limit database user permissions
- Enable SSL connections
- Regular backups
- Keep MySQL updated
- Monitor for suspicious activity
cd backend
# Run all tests
php artisan test
# Run specific test file
php artisan test tests/Feature/AuthenticationTest.php
# Run with coverage
php artisan test --coveragecd frontend
# Run all tests
npm run test
# Run in watch mode
npm run test:watch
# Run with coverage
npm run test:coverageContributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow existing code style
- Write tests for new features
- Update documentation
- Ensure all tests pass
- Keep commits atomic and descriptive
This project is licensed under the MIT License. You are free to use, modify, and distribute this software as long as proper credit is given.
For questions, issues, or feature requests, please open an issue on GitHub.
Built with:
- Laravel - Backend framework
- Next.js - Frontend framework
- Tailwind CSS - CSS framework
- MySQL - Database
- Laravel Sanctum - API authentication
Happy Coding!