Create dummy user credentials
Remember that Vercel automatically creates a new preview deployment for your feature branch whenever you initiate a pull request. This deployment is strictly for testing purposes and will have a different URL from your production deployment. Due to this URL discrepancy, the callback URL for your GitHub OAuth App will no longer match, necessitating an update to accommodate the new URL.
There are two different ways to work around this:
- On GitHub, you can register a separate OAuth App specifically for your preview deployment by setting a callback URL that points to it. Each time you create a new pull request, it's necessary to update the callback URL in the OAuth App settings to align with the URL of the current preview deployment. This ensures that the authentication process functions correctly with each new change.
pro | con |
---|---|
testing with multiple logins possible | need to adapt the OAuth settings for every new PR |
testing the GitHub login itself |
- In the
authOptions
, alongside yourGithubProvider
, you should include aCredentialsProvider
that features a dummy user (as shown in the code snippet below). This setup provides an additional login method via username and password. By defining only one dummy user ("fisch" in the example), you allow people to log in as this user for testing purposes. This approach simplifies testing by enabling access through a predefined user account.
pro | con |
---|---|
No need to adapt the OAuth settings | the dummy user is shared between different testers |
Examine the ternary operator
process.env.VERCEL_ENV === "preview" ? CredentialProvider : GithubProvider
This operator conditionally selects the CredentialsProvider
for preview deployments or the GithubProvider
for production environments.
This setup ensures that the appropriate authentication provider is used based on the deployment context.
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions = {
// Configure one or more authentication providers
providers: [
process.env.VERCEL_ENV === "preview"
? CredentialsProvider({
name: "credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "username" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (
credentials.username === "fisch" &&
credentials.password === "fisch"
) {
return {
name: "Neuer Fisch",
email: "test@example.com",
id: "a1b2c3d4"
};
} else {
return null;
}
},
})
: GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
// ...add more providers here
],
};
export default NextAuth(authOptions)