Next Auth doesn't work with custom basePath - next.js

My NextAuth are returning 404 when searching for api/auth/session at credential provider custom login, seems like Next Auth are pointing to the wrong url.
My next.config.js have a basePath that points to a subfolder basePath: '/twenty-test' and my NEXTAUTH_URL is already set to my subdomain,
but when I go to my credential provider login custom page (that was working at localhost because it was not at a subdomain), i see an 404 error at console like https://explample.com/api/auth/session 404.
This is my custom provider config:
providers: [
CredentialProvider({
name: 'Credentials',
type: 'credentials',
async authorize(credentials) {
//
if(credentials.email == "john#gmail.com" && credentials.password == "test"){
return {
id: 2,
name: 'John Doe',
email: 'john#gmail.com',
permition: {
group: 2,
level: 0
}
}
}
return null;
}
})
],
This is my next.config.js
const nextConfig = {
reactStrictMode: true,
basePath: '/twenty-test',
images: {
domains: ['example.com'],
},
}
module.exports = nextConfig
This is my NEXTAUTH_URL env variable
NEXTAUTH_URL="https://example.com/twenty-test/api/auth"
This is my getCsrfToken config
export async function getServerSideProps(context) {
return {
props: {
csrfToken: await getCsrfToken(context)
}
}
}
My project are not on vercel. I'm using a custom server config to deploy with cPanel

The problem was on building the app in localhost and deploying on server.
The app was building expecting NEXTAUTH_URL as localhost, and simply changing the .env variable on server didnt worked.
The solution was building the app on server.
Another workaround was replacing the localhost NEXTAUTH_URL ocurrences after building with the value of NEXTAUTH_URL on server.

Related

NextAuth.js signIn() method not working using serverless-http in AWS Lambda

I am trying to deploy NextJs and NextAuth.js to AWS using CDK (Cloud Development Kit). I have cloned the NextAuth.js example project (https://github.com/nextauthjs/next-auth-example) and
installed "serverless-http" for handling the binding from Lambda to NextJs. I attempted to follow this guide https://remaster.com/blog/nextjs-lambda-serverless-framework but using AWS CDK instead of the serverless.yml file as I am integrating it with existing infrastructure.
next.config.js:
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
unoptimized: true
},
output: 'standalone'
}
module.exports = nextConfig
[...nextauth].ts (From the example but using a simple credentials provider that always resolves):
import NextAuth, { NextAuthOptions } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
return { id: "1", name: "J Smith", email: "jsmith#example.com" }
}
})
],
theme: {
colorScheme: "light",
},
callbacks: {
async jwt({ token }) {
token.userRole = "admin"
return token
},
},
}
export default NextAuth(authOptions)
server.ts:
import { NextConfig } from "next";
import NextServer from "next/dist/server/next-server";
import serverless from "serverless-http";
// #ts-ignore
import { config } from "./.next/required-server-files.json";
const nextServer = new NextServer({
hostname: "localhost",
port: 3000,
dir: __dirname,
dev: false,
conf: {
...(config as NextConfig),
},
});
export const handler = serverless(nextServer.getRequestHandler());
It is being built using the following script:
#!/bin/bash
BUILD_FOLDER=.dist
yarn build
rm -rf $BUILD_FOLDER
mv .next/standalone/ $BUILD_FOLDER/
cp -r .next/static $BUILD_FOLDER/.next
rm $BUILD_FOLDER/server.js
cp -r next.config.js $BUILD_FOLDER/
cp -r node_modules/serverless-http $BUILD_FOLDER/node_modules/serverless-http
tsc server.ts --outDir .dist --esModuleInterop true
cp -r public $BUILD_FOLDER/
This is deployed using AWS written in CDK C#. Primarily using a HttpApi and a single Lambda. Each configured as shown below:
Lambda:
var function = new Function(this, "nextjs-function", new FunctionProps
{
Code = Code.FromAsset(...".dist"),
Handler = "server.handler",
Runtime = Runtime.NODEJS_16_X,
...
Environment = new Dictionary<string, string>
{
{ "NEXTAUTH_URL", "https://myDomainName.com" },
{ "NEXTAUTH_SECRET", portalSecret },
}
});
HttpApi:
var httpApi = new HttpApi(this, "http-api", new HttpApiProps
{
DisableExecuteApiEndpoint = true,
DefaultIntegration = new HttpLambdaIntegration("nextjs-route", function),
DefaultDomainMapping = new DomainMappingOptions
{
DomainName = "myDomainName.com"
}
});
Opening the deployed webpage and clicking the "Sign In" button at the top, I get taken to /api/auth/signin?callbackUrl=%2F with a form. Without touching the credentials I click "Sign in with credentials". This results in the page reloading and nothing happening. Expected behaviour should be a session and a redirect back to the home page (/) as is happening when running it locally using either yarn dev or yarn build && yarn start.
I get no errors client/server-side thus leaving me in the dark.
I suspect that it has to do with domain configuration but I am unable to find the problem. I tested with another NextJs/NextAuth project using a AWS Cognito provider. This also had problems as when I clicked the sign in button I got an "Unexpected token" error due to the underlying signIn(...) function (from the NextAuth library) trying to parse the fetched page as JSON, which turned out to be the sign-in-page. Thus my suspicion of something domain-related.

getting error when using nuxt 3 with nuxt auth module

I am using nuxt 3 + nuxt auth module
getting this error :
this is my nuxt config
export default defineNuxtConfig({
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next'
],
auth: {
strategies: {
cookie: {
cookie: {
// (optional) If set, we check this cookie existence for loggedIn check
name: 'XSRF-TOKEN',
},
endpoints: {
// (optional) If set, we send a get request to this endpoint before login
csrf: {
url: ''
}
}
},
}
}
})
what is the problem ?
The auth module is currently not supported by Nuxt3 but it is planned on the roadmap.
https://v3.nuxtjs.org/community/roadmap#%EF%B8%8F-roadmap
Latest official update: https://twitter.com/Atinux/status/1570317156033642496?t=YNN0iWL6M5l3Z0xm_ernCg&s=19

How to rewrite homepage based on hostname

I'd like to show two different pages at '/' depending on the hostname (the value for req.hostname). This is because I have a subdomain xxx.mydomain.com that needs to show just one page at the root URL. The idea is to have a CNAME for the subdomain that points to the same server as www. I'm using next version 11.1.2 .
My homepage (/pages/index.js) uses getStaticProps to get data for the page with a revalidate interval of 2 seconds. The page on the production branch works great currently without any rewriting.
I tried using the rewrites option in next.config.js and was able to use this to rewrite all other routes, but rewriting with source: '/' did not do anything. If the source was any other page it worked perfectly. This is pretty much what the next.config.js file looked liken when I tried the rewrite:
const withFonts = require('next-fonts');
const withTM = require('next-transpile-modules')(['#cal-frontends/shared']);
require('dotenv').config({ path: '../../.env' });
module.exports = withTM(withFonts({
async rewrites() {
return [
{
source: '/', // this one still showed the homepage at '/'
destination: '/mission',
},
{
source: '/foo', // this one showed the contact page at '/foo'
destination: '/contact',
},
]
},
webpack(config, options) {
return config;
},
}));
I tried many strategies, including this kind of configuration in server.js
server.get('/',function(req,res){
console.log('trying to redirect', )
console.log('req.hostname', req.hostname)
if (req.hostname === 'mission.mydomain.com') {
console.log('this should show mission', )
return app.render(req, res, '/mission', {})
} else {
handle(req, res);
}
});
This unfortunately did not seem to override the static caching that happens with getStaticProps – you will only see the correct page for the hostname if you load and then reload after it revalidates.
Is there an elegant way to do this?

Amplify CDK with Next.js SSR

I am trying to deploy a next.js (ssr) application in AWS' Amplify using the CDK but Amplify fails to identify the app as next.js ssr. When I do it manually though, using AWS UI, app is identified as SSR and works as expected.
This is generated by aws-cdk/aws-amplify v118 as:
import * as cdk from '#aws-cdk/core';
import * as amplify from '#aws-cdk/aws-amplify';
import codebuild = require('#aws-cdk/aws-codebuild');
export class AmplifyStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: cdk.StackProps) {
super(scope, id, props);
const sourceCodeProvider = new amplify.GitHubSourceCodeProvider({
owner: '.....',
repository: '....',
oauthToken: cdk.SecretValue.secretsManager('github-token'),
});
const buildSpec = codebuild.BuildSpec.fromObjectToYaml(
{
version: 1,
applications: [
{
frontend: {
phases: {
preBuild: {
commands: [
"npm install"
]
},
build: {
commands: [
"npm run build"
]
}
},
artifacts: {
baseDirectory: ".next",
files: [
"**/*"
]
},
cache: {
paths: [
"node_modules/**/*"
]
}
}
}
]
}
);
const amplifyApp = new amplify.App(this, "cdk-nf-web-app", {
sourceCodeProvider: sourceCodeProvider,
buildSpec: buildSpec
});
amplifyApp.addBranch('develop', {
basicAuth: amplify.BasicAuth.fromGeneratedPassword('dev')
});
amplifyApp.addCustomRule({
source: "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>",
target: "/index.html",
status: amplify.RedirectStatus.REWRITE
});
}
}
Which is identical to what AWS has generated when I do it manually from UI. The difference here is the lack of Framework identification as shown in picture. Any ideas?
To answer my own question, I was missing the role as without it aws won't create the necessary resources. (role: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html)
Edit to elaborate on how i fixed it:
Added a new role that can be used by amplify
const role = new iam.Role(this, 'amplify-role-webapp-'+props.environment, {
assumedBy: new iam.ServicePrincipal('amplify.amazonaws.com'),
description: 'Custom role permitting resources creation from Amplify',
});
and assigned a policy (AdministratorAccess) that role
let iManagedPolicy = iam.ManagedPolicy.fromAwsManagedPolicyName(
'AdministratorAccess',
);
role.addManagedPolicy(iManagedPolicy)
Then upon creating the app, i assigned the role to the app:
const amplifyApp = new amplify.App(this, "cdk-nf-web-app", {
sourceCodeProvider: sourceCodeProvider,
buildSpec: buildSpec,
role: role <--- this line here
});
The amplify app requires authorisation to create the relevant resources:
// This is for demonstrations purposes only; Do not give full access for production usage!
amplifyApp.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
resources: ["*"],
actions: ['*'],
}))
Source Code Showcase

Next.js redirect www to non www

I have been trying to find a workable solution this searching google but can't find anything solid. I am hosting my Next.js application on Vercel.
When I run a seo check it moans about me having the site available on www and non www and says I should pick one and get it to redirect so in my case, if someone types in www.example.com I would prefer it left of the www.
Since I don't have a htaccess file I can do this in, how would I do it?
Not sure if it matters, but I am using WordPress as my backend aka: Headless Wordpress
You should be able to use host-based redirects now since Next v10.2. See https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching.
In next.config.js:
module.exports = {
// ...
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'www.yourdomain.com' }],
destination: 'https://yourdomain.com/:path*',
permanent: true
}
]
}
you can easily handle permanent redirection in nextjs using the below-mentioned code.
export const getServerSideProps = async (context) => {
const { req, res } = context;
if (req.headers.host.match(/^www/) !== null) {
res.writeHead(301, {
location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
});
res.end();
}
return { props: {} };
};

Resources