getting error "this.getHeaders is not a function" on website - next.js

I just updated to next js v13 and I am get this error when I visit my website home page.
this file is causing the error
middleware.js
import { NextResponse } from 'next/server'
export default function Middleware(req) {
if (req.nextUrl.pathname !== req.nextUrl.pathname.toLowerCase()) {
const url = req.nextUrl.clone()
url.pathname = url.pathname.toLowerCase()
return NextResponse.redirect(url)
}
return NextResponse.next()
}
when i deleted this file my website worked and the error went away.
next js v13 made changes to middlewares: https://nextjs.org/blog/next-13#middleware-api-updates but i'm not sure how it affected my code
update: i just saw this in the next js v13 blog and made the changes but the error is still happening
Sending responses from Middleware currently requires the experimental.allowMiddlewareResponseBody configuration option inside next.config.js.
next.config.js.
const nextConfig = {
reactStrictMode: true,
experimental: {
allowMiddlewareResponseBody: true
},
}

Related

Nextjs build successful on netlify but site css not accessible

My Nextjs site builds without error on netlify. But the site looks like this and does not pick up the css. The console shows a syntax error Uncaught SyntaxError: Unexpected token '<'. The routing also does not work.
This site works fine when deployed to vercel. When I run npm run build and npm run start locally it works fine too. My scripts in package.json are as follows
"scripts": {
"dev": "next dev",
"start": "next start",
"build": "next build"
},
Previously I was using next build && next export to build my site but now I need Incremental Static Regeneration which is not supported by next export.
My netlify deploy settings are as
follows
When I use next export a link to any dynamic page that is not in getStaticPaths takes me to the home page. If I go to the url from inside the application, it works fine but a refresh takes me back to the home page. When I remove next export I am faced with the above issue in netlify.
my dynamic page code stripped down is as follows
[tag].js
import Head from "next/head";
import SearchPage from "../../components/app/SearchPage/SearchPage";
import {
fetchAllCuratedTopicsToRender,
fetchTitleAndDescription,
} from "../../services/SearchService";
const Search = ({ title, meta_description }) => {
const defaultTitle = "default title";
const defaultMetaDescription = "default meta description";
return (
<>
<Head>
<title key="title">{title || defaultTitle}</title>
<meta
name="description"
content={meta_description || defaultMetaDescription}
key="description"
/>
</Head>
<SearchPage />
</>
);
};
export default Search;
// Generates all the paths for the curated topics stored in the database
export async function getStaticPaths() {
const APIresponse = await fetchAllCuratedTopicsToRender();
const allPaths = APIresponse.map((el) => {
return { params: { tag: el.keyword } };
});
return {
paths: [...allPaths],
fallback: "blocking",
};
}
export async function getStaticProps(context) {
let titleAndDescription = {
title: "",
meta_description: "",
};
// only get title and description if there is a tag in the url
if (context.params?.tag) {
const tag = context.params.tag.toString();
titleAndDescription = await fetchTitleAndDescription(tag);
}
return {
props: {
title: titleAndDescription.title || "",
meta_description: titleAndDescription.meta_description || "",
},
revalidate: 31536000,
};
}
This would be a case of you having a redirect rule like:
/* /index.html 200
in your public folder. Statically generated sites sometimes needed that for client-side only navigation, but it won't be needed if you're using server-side stuff (including ISR). The Netlify Next.js Runtime also warns about this in your build logs. Simply removing the rule should fix it.

Headers are removed from middleware in production Next js

I have such a strange thing. Project on next js 12.3. I use middleware to add canonical link to headers. Everything works locally, and the required headers are added, but when deployed in production, the header I need is not added.
if the subdomain is not www, the canonical must be a link to the www version
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest, res: NextResponse) {
const { protocol, href } = req.nextUrl;
const subdomain = href.replace('https://','').split('.')[0];
if (subdomain !== 'www') {
const urlArr = href?.split('//');
const afterSubdomainUrl = urlArr?.slice(1, urlArr.length)?.join('//');
const response = NextResponse.next();
response.headers.append(
'Link',
`<${protocol}//www.${afterSubdomainUrl}>; rel="canonical"`,
);
return response;
}
}
The problem was at DockerFile - need to implement next code at
app/Dockerfile
COPY middleware.ts /app/middleware.ts
RUN true

Identifier 'module' has already been declared - amplify and nuxt 3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?
Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});
I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

NextJS config: Move redirects to it's own file

I'm moving from a wordpress site to a new, shiny nextjs site. However, I have hundreds of redirects and I don't want to put them all in the nextjs config file. I like things clean and tidy. I searched around for awhile and didn't find any results on how to do this. Any suggestions?
You need to import it via require, tho remember that u also need to export it as module, so ex.:
const redirectsArray = [
{ source: "/about", destination: "/", permanent: true },
];
async function redirects() {
return redirectsArray;
}
module.exports = {
redirects,
};
and then
const { redirects } = require("./redirects.js");
I got it working while module exporting it as an array instead of an object in the redirects.js
module.exports = redirects
And then add it to the next.config.js like so
async redirects() {
return redirects
}

Next.js returns 500: internal server error in Production

Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!

Resources