Next.js Discord

Discord Forum

How to send axios request to next auth secured route?

Unanswered
Iridescent shark posted this in #help-forum
Open in Discord
Original message was deleted.

10 Replies

Original message was deleted
First of all, avoid using axios. https://adios-axios.com/

Can you send your code
@Anay-208 First of all, avoid using axios. https://adios-axios.com/ Can you send your code
Iridescent shark
axios.ts
import axios, { CreateAxiosDefaults } from "axios";
const config: CreateAxiosDefaults = {
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
};
const instance = axios.create(config);
export default instance;

NextAuthOptions. Here I'm trying to attach jwt token to axios requests.
export const options: NextAuthOptions = {
  // Configure one or more authentication providers
  adapter: PrismaAdapter(db),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID as string,
      clientSecret: process.env.GOOGLE_SECRET as string,
    }),
  ],
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.sub!;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }

      return token;
    },
    signIn: (params) => {
      axios.interceptors.request.use(
        (config) => {
          config.headers.Authorization = `Bearer ${params.account?.access_token}`;
          return config;
        },
        (error) => {
          return Promise.reject(error);
        }
      );

      return true;
    },
    redirect: () => {
      return "/library";
    },
  },
  session: {
    strategy: "jwt",
  },
};

my POST route. Session is null here
export async function POST(req: NextRequest) {
  console.log(req);
  const session = await getSession(); <- it is null

  const body = await req.json();

  const set = setFormSchema.parse(body);

  const createdSet = await db.set.create({
    data: {
      title: set.title,
      description: set.description,
      textLang: set.textLang,
      definitionLang: set.definitionLang,
      image: set.image,
      userId: session!.user.id,
    },
  });

  return NextResponse.json(
    { id: createdSet.id },
    {
      status: 201,
    }
  );
}
withCredentials just forwards your cookie if I'm right
if it requires headers, do this
import axios from 'axios';

const response = await axios.get('https://your-secured-route.com', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});
Iridescent shark
I attach header inside signIn callback

signIn: (params) => {
      axios.interceptors.request.use(
        (config) => {
          config.headers.Authorization = `Bearer ${params.account?.access_token}`;
          return config;
        },
        (error) => {
          return Promise.reject(error);
        }
      );

      return true;
    },
@Anay-208 `withCredentials` just forwards your cookie if I'm right
Iridescent shark
I tried to set session strategy to default, I guess it's cookie. And frontend part didn't work at all. It always redirected to the sign-in page
I’ve a suggestion. Fetch api works the best with nextjs. Recommending you to use that, most of the people use that only.
And for the error part, since I’m not familiar with these functions of axios, I’d prefer someone else to help with this
@Anay-208 I’ve a suggestion. Fetch api works the best with nextjs. Recommending you to use that, most of the people use that only.
Iridescent shark
Do you know how can I get access token in next auth?
That isn't axios problem I attached both cookies and jwt tokens many times and it worked fine