How to add session to request (nextAuth)?
Unanswered
Orinoco Crocodile posted this in #help-forum
Orinoco CrocodileOP
I am using Next Auth for authorization. After authorization I have session with accessKey. How can I add accessKey to protected request to the server?
Cannot find name 'res'
import { getServerSession } from "next-auth/next"
import { authOptions } from "src/app/api/auth/[...nextauth]/route";
axios.interceptors.request.use(
async (config) => {
const session = await getServerSession(req, res, authOptions)
if (session?.accessToken) {
config.headers.authorization = `Bearer ${session?.accessToken}`
}
return config;
},
(error) => Promise.reject(error)
);Cannot find name 'res'
53 Replies
getServerSession itself uses cookies and headers under the hood
axios.interceptors.request.use(
async (config) => {
const session = await getServerSession(req, res, authOptions)
if (session?.accessToken) {
config.headers.authorization = `Bearer ${session?.accessToken}`
}
return config;
},
(error) => Promise.reject(error)
);what are you trying to do here?
@alfon ts
axios.interceptors.request.use(
async (config) => {
const session = await getServerSession(req, res, authOptions)
if (session?.accessToken) {
config.headers.authorization = `Bearer ${session?.accessToken}`
}
return config;
},
(error) => Promise.reject(error)
);
what are you trying to do here?
Orinoco CrocodileOP
Let's say I have a secure api. I need to add accessKey headers. How can I get it in the interceptor?
config.headers.authorization = `Bearer ${data?.accessKey}
like this
like this
is the secure api in nextjs or external server?
Orinoco CrocodileOP
External server
i see
Orinoco CrocodileOP
For example get list of posts for specific user
is your nextauth using db or jwt?
Orinoco CrocodileOP
jwt
i dont think there is access key with jwt :/
unless you put it there manually
Orinoco CrocodileOP
the user logs in, the server sends me an accessKey ( jwt token ). And I put it in a session. And I have a dilemma, how to make secure requests and put accessKey in these requests so that 401 errors are not returned
which server? external or next-auth
Orinoco CrocodileOP
External - for example some secret information from backend
ah so the jwt is decrypted in external server not from nextauth
Orinoco CrocodileOP
I don't understand 😦
I don't need decrypte, I just need send it with some request
how did you validate user info if you don't decrypt it?
the way jwt works is that you need to send the whole jwt in EVERY request as opposed of Bearer Token
and the server (whoever receiving client jwt) will decrypt it and validate it if user is valid or not. if valid -> authenticated
the decrypted result of JWT is a payload that contains summarized user info
@alfon how did you validate user info if you don't decrypt it?
Orinoco CrocodileOP
Server send me name, emal and accessKey
Backend*
hmmm in the form of JWT right? i hope not in POJO :''))
Orinoco CrocodileOP
It is just json
so its not jwt :/
so why can't you just access the accessKey inside the json?
if ure using jwt in NextAuth i may need to see your jwt() callback inside authOption
@alfon so its not jwt :/
Orinoco CrocodileOP
why? it is contains accessKey
@alfon if ure using jwt in NextAuth i may need to see your jwt() callback inside authOption
Orinoco CrocodileOP
okey one sec
thats not what jwt is 🥹
Orinoco CrocodileOP
const providers = [
CredentialsProvider({
type: 'credentials',
credentials: {},
authorize: async (credentials) => {
try {
const { email, password } = credentials as any
const user = await axios.post(process.env.URL)
// const user = {
// data: {
// status: true,
// message: '',
// payload: {
// name: 'user',
// email: 'usera@mail.ru',
// accessKey:
// 'wRByOblxUkYENRm4UGBjZWKazX',
// },
// },
// } /// this is what server return
if (user.data.payload.accessKey) {
return user.data.payload
}
} catch (e) {
console.log(e)
}
},
}),
]
export const authOptions: NextAuthOptions = {
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt',
maxAge: 30 * 86400,
},
providers: providers,
pages: {
signIn: '/auth/login',
},
callbacks: {
jwt: async ({ token, user, account, profile }) => {
if (user) {
token.accessKey = user.accessKey
}
return token
},
async signIn({ user, account, profile, email, credentials }) {
return true
},
session: async ({ session, token, user }) => {
session.accessKey = token.accessKey
return session
},
},
}ah its in the token
getServerSession returns a session object not the token
then the token is passed to session() callback
accessKey is already in the session
it should be in the getServerSession() already then
is it not working? any error?
@alfon is it not working? any error?
Orinoco CrocodileOP
Not errors, but how can I add my accessKey in every protercted request?
where did you call the request?
next.js server? browser?
Orinoco CrocodileOP
I found this article
ANd in this case person doesn't use next auth, but I use
import axios from "axios";
import { memoizedRefreshToken } from "./refreshToken";
axios.defaults.baseURL = "http://localhost:3333/api";
axios.interceptors.request.use(
async (config) => {
const session = JSON.parse(localStorage.getItem("session"));
if (session?.accessToken) {
config.headers = {
...config.headers,
authorization: `Bearer ${session?.accessToken}`,
};
}
return config;
},
(error) => Promise.reject(error)
);ANd in this case person doesn't use next auth, but I use
I need the same but with Next auth 

Orinoco CrocodileOP
Are you here?

Orinoco CrocodileOP
in the browser
Great black wasp
Dont need no interceptor just use middleware to set acesstoken header and decode jwt and point it to api route that need authentication
You need to validate first before setting the header
@Orinoco Crocodile in the browser
you can get the accessToken of a session using
useSession()or getSession() but this will manually fetch to nextjs backend per call