Updated on: Wed Jul 14 2021
Hey! Here we will implement some authentication functionality via our technology friends mentioned in title. We will start right from implementation. If you wanna find information regarding initial setup then most probably you will have good overview after reading first part of tutorial.
We can start from initial implementation of auth for example for twitter. This code listing goes directly to /pages/api/auth/[...nextauth].ts:
copied ts/tsx
import { NextApiHandler } from "next";
import NextAuth, { InitOptions } from "next-auth";
import Adapters from "next-auth/adapters";
import Providers from "next-auth/providers";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const options: InitOptions = {
secret: process.env.AUTH_SECRET,
providers: [
Providers.Twitter({
clientId: process.env.TWITTER_CLIENT_ID,
clientSecret: process.env.TWITTER_CLIENT_SECRET,
}),
],
adapter: Adapters.Prisma.Adapter({
prisma,
}),
};
const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;
After that let's go and use that auth api in our client side code. We have to wrap our app with Provider from next-auth/client somewhere in the root of our App. File /pages/_app.tsx suits this purpose very well.
copied jsx
import { AppProps } from "next/app";
import { Provider } from "next-auth/client";
const MyApp = ({ Component, pageProps }: AppProps) => {
return (
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
);
};
export default MyApp;
Important thing to know is that next-auth wants special url schema to be setup in providers consoles. Especially http://localhost:3000/api/auth/callback/{provider} will go to callback or redirect url field. And http://localhost:3000 goes to authorised url field. This is for sure during development stage. We will specify different ones in vercel dashboard's env section when go live.
Twitter and Google apps setup will be explained in detail in different tutorial. Stay tuned. Let's just provide here urls to google cloud console and twitter developer portal.
For now it's enough to mention that url http://localhost:3000/api/auth/callback/twitter goes to allowed callback urls list there during development.
For google process would be almost the same except http://localhost:3000/api/auth/callback/google needs to be added to allowed redirect urls field. And we also have to add our test users emails in Oauth consent screen section.
Final result could be found in this boilerplate repo.