Skip to content

Instantly share code, notes, and snippets.

@exocode
Forked from RafalFilipek/[...nextauth].ts
Created September 27, 2022 18:05
Show Gist options
  • Save exocode/95b892397e75259c1ace8172f35aa310 to your computer and use it in GitHub Desktop.
Save exocode/95b892397e75259c1ace8172f35aa310 to your computer and use it in GitHub Desktop.
Hasura + next-auth
import NextAuth, { type NextAuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import * as jwt from "jose";
export const authOptions: NextAuthOptions = {
// the rest is just like in tutorials. Session, callbacks etc.
jwt: {
encode: async ({ secret, token }) => {
if (!token) {
console.warn("encode: No token provided");
}
return await new jwt.SignJWT(token!)
.setProtectedHeader({ alg: "HS256" })
.sign(new TextEncoder().encode(secret as string));
},
decode: async ({ secret, token }) => {
if (!token) {
console.warn("decode: No token provided");
}
const { payload } = await jwt.jwtVerify(
token!,
new TextEncoder().encode(secret as string),
{ algorithms: ["HS256"] }
);
return payload as JWT;
},
},
// the rest is just like in tutorials. Session, callbacks etc.
};
export default NextAuth(authOptions);
export async function getServerSideProps(context: GetServerSidePropsContext) {
// decoded token
const token = await getToken({
req: context.req,
decode: authOptions.jwt?.decode,
});
// raw token
const raw = await getToken({ req: context.req, raw: true });
return {
props: {
token,
raw,
session: await unstable_getServerSession(
context.req,
context.res,
authOptions
),
},
};
}
import withAuth from "next-auth/middleware";
import * as jwt from "jose";
import { JWTDecodeParams } from "next-auth/jwt";
async function decode({ secret, token }: JWTDecodeParams) {
if (!token) {
console.log("middleware-decode: No token provided");
}
const { payload } = await jwt.jwtVerify(
token!,
new TextEncoder().encode(secret as string),
{
algorithms: ["HS256"],
}
);
return payload;
}
export default withAuth({
jwt: { decode },
callbacks: {
authorized: ({ token }) => !!token,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment