In modern web applications, sometimes necessary to use separate backend and frontend applications. However, this approach can lead to problems such as CORS (Cross-Origin Resource Sharing) errors. To overcome these problems, you must create a convenient development environment.
In this article, we will configure our Laravel application to function as an API service and set up our frontend NextJS application to run on our root domain. I will be using Laragon as my web server, and for setting up a reverse proxy, we will use Apache configurations.
Configuring Our Backend
Open your backend Apache conf file and add api.
subdomain to your project url.
- define SITE "project.test"
+ define SITE "api.project.test"
Add your project url in hosts file.
+ 127.0.0.1 api.project.test
**Don’t remove your old registery we will use that for frontend.
In your cors.php config file you have to update supports_credentials
to true.
- 'supports_credentials' => false,
+ 'supports_credentials' => true,
**Don’t forgot to add your sanctum or other endpoints to paths
array in cors.php
config.
Add your project url to .env file if you are using sanctum.
+ SANCTUM_STATEFUL_DOMAINS=api.project.test
Now your backend project is ready to use. You have to configure your frontend.
Configuring Our Frontend
This part can be achived with reverse proxy configuration or settting hostname and port in your frontend framework.
Reverse Proxy:
Create apache configuration file for your frontend. This conf. file going to proxy your frontend url.
define ROOT "C:/laragon/www/project-fe/public"
define SITE "project.test"
<VirtualHost *:80>
ProxyPass / http://localhost:3000/ # This line
ProxyPassReverse / http://localhost:3000/ # This line
ServerName ${SITE}
ServerAlias *.${SITE}
</VirtualHost>
If you removed your backend registery then add this to your hosts file. Otherwise you can skip this step.
+ 127.0.0.1 project.test
Setting Hostname and Port Configuration:
To change hostname and port in NextJS, you can use -p and -H parameters. For example, open your package.json
and add this line:
...
"scripts": {
- "dev": "next dev",
+ "dev": "next dev -p 80 -H project.test",
...
},
...
Testing
Now you can run your projects and open api.project.test
and project.test
urls to test your application.
Top comments (0)