Table of contents
Preface
My tech stack is Next.js and Node.js. I use next rewrites
to resolve the CORS problem, which allows my application to communicate with external APIs without facing cross-origin issues.
CORS
To resolve the CORS problem, put the following code in
next.config.js
:
async rewrites() {
return [
{
source: "/api/:path*",
destination:
process.env.NEXT_PUBLIC_ENV === "PRD"
? process.env.NEXT_PUBLIC_PRD_API_URL + "/api/:path*"
: process.env.NEXT_PUBLIC_STG_API_URL + "/api/:path*",
},
];
},
Auth
This section covers how to support third-party providers such as Google and GitHub, including configurations for both frontend and backend.
3rd party
Take Github for example:
- Host URL should point to the Frontend Home URL.
- Call back URL
- Must be HTTP.
- The host is also the Frontend.
- ex: http://xx/auth/github/redirect.
Frontend
- Add buttons for each provider
- Handle the callback from the provider, which is the backend host callback URL.
Backend
In the backend, I use Passport.js and JSON Web Tokens (JWT) to handle authentication.
-
Passport.js: This library is used to implement various authentication strategies for different providers, such as Google and GitHub.
- For each provider, I create a strategy that utilizes the profile ID to create a new
User
in the database if they do not already exist.
- For each provider, I create a strategy that utilizes the profile ID to create a new
-
JWT: After successful authentication, I generate a JWT for the user. This token is then verified for subsequent requests to ensure the user is authenticated.
- The JWT is sent as a cookie to the frontend, allowing for secure session management.
After the authentication process, we can redirect the user to the Frontend Home URL
, providing a seamless user experience.