How can I access session in the API backend?
I'm using credential authentication and would like to access the session token on the API backend. Unfortunately, getSession or session doesn't seem to work. How best should I proceed?
Documentation feedback
Hi there!
Take a look at the example project, which is using the v3 beta.
It has examples of how to get the session from an API route.
For v3 it looks like this:
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
console.log('session', session)
res.end()
}
It's currently slightly different in v2 as you need to call setOptions():
import { setOptions, getSession } from 'next-auth/client'
setOptions({ site: process.env.SITE })
export default async (req, res) => {
const session = await getSession({ req })
console.log('session', session)
res.end()
}
i cant seem to get this to work using 2.2.0 is there something magic i'm missing?
import { getSession, setOptions } from 'next-auth/client';
export default async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<any> => {
try {
const session: NextAuthSession = await getSession({ req });
console.log('sesssion in api is', JSON.stringify(session, 4, null));
if (!session) {
return noPremsResponse(res, 'Session aint right');
}
...
Session is ALWAYS null. no matter if which version of your snippet i use.
Actually, this doenst. work. Ignore this comment.
To add to this, if i create my own 'getSession' like this:
```/**
${process.env.SITE}/api/auth/session);i've started to add some debugging to the dist of next-auth to try and narrow it down.
import { getSession, setOptions } from 'next-auth/client';
import { NextApiRequest, NextApiResponse } from 'next';
import { successResponse } from '../../../../lib/apiResponses';
import { NextAuthSession } from '../../../../types';
setOptions({ site: process.env.SITE });
/**
* Get the User details
*/
export default async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<any> => {
try {
const session: NextAuthSession = await getSession({ req });
console.log('sesssion in api is', JSON.stringify(session, null, 4));
} catch (err) {
console.log('YOu have an error', err);
}
return successResponse(res, {});
};
This is my super basic endpoint, as per your example above. I have added the following console.log to the dist of next-auth client/index.js
var baseUrl = _baseUrl();
console.log('BaseURL in client is', _baseUrl());
var options = req ? {
headers: {
cookie: req.headers.cookie
}
} : {};
var session = yield _fetchData("".concat(baseUrl, "/session"), options);
console.log('Session is now', session, 'options are', options);
The console.log out put for this request is:
BaseURL in client is http://localhost:3001/api/auth
event - build page: /api/auth/[...nextauth]
wait - compiling...
info - ready on http://localhost:3001
Session is now null options are { headers: { cookie: undefined } }
sesssion in api is null
But, if i call the getSession() hook on the client i get the following output:
BaseURL in client is http://localhost:3001/api/auth
Session is now {
user: { name: null, email: '[email protected]', image: null },
accessToken: '[some-access-token-string]',
expires: '2020-08-25T00:00:00.000Z'
} options are {
headers: {
cookie: 'next-auth.csrf-token=[csrftoken]; next-auth.callback-url=[callback-url]; next-auth.session-token=[session-token]'
}
}
Something is defo up, but i dont know what nor do i know where it is. i SHOULD be able to getSession in an API. Otherwise what's the point? :(
Right, ok, so i've solved the issue it was probably an issue with my understanding on how things work in Next. I forgot to pass down the headers from the context within getServerSideProps.
export async function getServerSideProps(context) {
const apiData = await fetch(
`${process.env.SITE}/[path-to-api]`,
{
headers: context.req.headers,
},
);
i now get the session within the API. now i just need to solve: console.log(apiData.json) showing <pending> but that's once again an issue with my lack of knowledge.
Hopefully this helps someone like me a n00b.
Most helpful comment
Hi there!
Take a look at the example project, which is using the v3 beta.
It has examples of how to get the session from an API route.
For v3 it looks like this:
It's currently slightly different in v2 as you need to call
setOptions():