Exportpathmap in next.config.js set dynamic routes in NextJS - javascript

I am trying to set dynamic routes by using Exportpathmap() in nex.config.js. Static routes is working fine as I want but when I am trying to apply dynamically, the dynamic URL is not working and redirected me to main URL.
Please help me do fix this issue.
Thansk in advance.
Here is my next.config.js
return{
reactStrictMode: true,
env: env,
trailingSlash : true,
eslint: {
ignoreDuringBuilds: true,
},
swcMinify: true,
images: {
domains: ['cdn.pixabay.com', 'pixabay.com', 'cdn.landrrapp.io'],
loader: 'akamai',
path: '',
},
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/404': { page: '/404' },
'/forgot-password': { page: '/forgot-password' },
'/login': { page: '/login' },
'/editor/[id]': { page: '/editor/[id]' },
}
},
}
I am facing issue with this one '/editor/[id]': { page: '/editor/[id]' },
NEXT JS: Build exportPathMap for a dynamic page Route
Above was lokks fine but I am unable to understand "
import { PAGE_ROUTES } from '../constants/config';
" this file data.

Related

Permanent redirect for www to non-www site using NextJs

I've built a website with Nextjs (using version 12.1.4). For SEO purposes I would like to make a permanent redirect for my www version of the site to my non-www. Normally this could easily be done with nginx or an .htaccess file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I've read that this should be possible using Nextjs redirects.
I've tried the following 3 redirects:
redirects: async () => [
{
source: '/:path*',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*',
permanent: true,
},
],
---------------------------------------------------
redirects: async () => [
{
source: '/:path*/',
has: [
{
type: 'host',
value: 'www',
},
],
destination: '/:path*/',
permanent: true,
},
],
------------------------------------------------------
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
destination: 'https://cvtips.nl/:path*',
permanent: true,
},
],
All of them don't seem to redirect to the non-www version. I don't know if it is relevant, but I do use trailingSlash: true in the config.
Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js and inside the pages folder calling it _middleware.js.
This is the code I use for the redirect:
--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
const host = req.headers.get('host');
const wwwRegex = /^www\./;
// This redirect will only take effect on a production website (on a non-localhost domain)
if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
const newHost = host.replace(wwwRegex, '');
return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
}
return NextResponse.next();
}
Also does not work at all... Doesn't do anything I believe.
How can I redirect a Nextjs website from www to non-www?

Vue 3, vite vue.esm-bundler.js build breaks jQuery

So I'm using vite to build my Vue 3 application for a legacy website which still uses jQuery and a few other JS frameworks.
I'm using the esm bundler as I would still like to boot it up and use it with slotted components.
<div id="app">
<vue-component-name></vue-component-name>
</div>
And it works perfectly. But when jQuery is used on the page, no where near my components it seems the esm bundled version of Vue has set a global variable named $ which breaks jQuery.
Has anyone had this issue or know of a way to fix it?
import { defineConfig } from 'vite';
import type { UserConfig as VitestUserConfigInterface } from 'vitest/config';
import svgLoader from 'vite-svg-loader';
import vue from '#vitejs/plugin-vue';
import path from 'path';
const vitestConfig : VitestUserConfigInterface = {
test: {
globals: true,
include: ['./tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
},
};
export default defineConfig({
test: vitestConfig.test,
plugins: [vue(), svgLoader()],
base: '/',
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
'#': path.resolve(__dirname, '/src'),
},
},
build: {
outDir: '../wwwroot/dist',
emptyOutDir: true,
manifest: true,
rollupOptions: {
input: {
main: './src/main.ts',
},
output: {
entryFileNames: 'assets/js/[name].js',
chunkFileNames: 'assets/js/[name].js',
assetFileNames: ({ name }) => {
if (/\.(gif|jpe?g|png|svg)$/.test(name ?? '')) {
return 'assets/images/[name][extname]';
}
if ((name ?? '').endsWith('.css')) {
return 'assets/css/[name][extname]';
}
return 'assets/[name][extname]';
},
globals: {
vue: 'Vue',
},
},
},
},
server: {
hmr: {
protocol: 'ws',
},
},
});
EDIT:
More information, I've tracked this down to using
#input="handleInput($event.target, index)"
This right here breaks existing jQuery. Still no idea how to get around it
For anyone interested, How to wrap Vite build in IIFE and still have all the dependencies bundled into a single file?

Cypress environment variable undefined

In cypress.json file i have the following code
{
"baseUrl": "test",
"ignoreTestFiles": [],
"viewportHeight": 768,
"viewportWidth": 1024,
"video": false,
"env": { "email": "test#email.com", "password": "password" }
}
When i am trying to access it by calling Cypress.env('password') it shows undefined in console log when printing it, what is the issues.
const password: string = Cypress.env('password')
describe("Login to the application", () => {
beforeEach(() => {
cy.visit("/");
});
it.only("user should login successfully", () => {
console.log(Cypress.env('email')). --- undefined
loginPage.login(email, password);
cy.url().should("include", "/wallet");
});
My mistake for not knowing or not checking the location of my cypress.json file, moved it to the top cypress folder and value is shown properly.
In my Projekt (Version 10.xx) the cypress.config.ts must be in the root path not in the cypress folder. You can generate the config with the UI, to get it on the right location:
Settings > Project settings > cypress.config.ts
UPDATE for CYPRESS V10.
Extending #Artjom Prozorov answer,
Now in the newer version the cypress.json naming convention is deprecated.
So, we have to use cypress.config.ts as file name for configuration.
sample of file content given below.
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
specPattern: "src/**/*.cy.{js,jsx,ts,tsx}",
baseUrl: "http://localhost:3001",
trashAssetsBeforeRuns: false,
viewportWidth:1920,
viewportHeight:1080,
slowTestThreshold: 1000,
// watchForFileChanges : false,
env: {
apiUrl : "http://localhost:3000",
commandDelay: 100,
password: 'here it is'
},
reporter: 'mochawesome',
reporterOptions: {
reportDir: 'cypress/reports',
overwrite: false,
html: true,
json: false
},
setupNodeEvents(on, config) {
config.env.sharedSecret =
process.env.NODE_ENV === 'development' ? 'itsDev' : 'itsLocal'
return config
}
},
component: {
devServer: {
framework: "create-react-app",
bundler: "webpack"
}
}
});
NOTE : this cypress.config.ts must be inside the cypress directory.

Why Proxy not working in browser (NuxtJS+Axios)?

In server rendering Proxy is working fine. Request is going to custom-server.com/v1/places. But in browser request is going to current-domain.com/api/places
Why it is not working in browser? Proxy working only in server side? Please, help.
I have NuxtJS config:
require('dotenv').config();
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
credentials: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : "/v1"
},
changeOrigin: true,
},
},
}
My component:
<script>
export default {
data() {
return{
placesServer:false,
placesBrowser:false,
}
},
async asyncData ({ $axios }) {
// Here is all is fine
let response = await $axios.get("/api/places");
return {
placesServer:response.data,
};
},
created(){
if (process.browser){
// Here is not working =(
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}else{
// Here is working fine!
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}
}
}
</script>
If your API URL is =http://custom-server.com/api/v1/api/places
Need to following change of Given code and need to understand the vuejs/Nuxtjs lifecyle
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : ""
},
},
},
}
and the given code inside created() hook is need to change another life cycle maybe. or need to move inside method() or as per need your requirements.
adding prefix to axios in nuxt.config.js helped me
axios: {
proxy: true,
credentials: true,
prefix: '/api/'
}

react-loadable and server side rendering with webpack 3

I am using react-loadable for react-router-v4and I want to do server side rendering.
Of course on server side I need not lazy loading, so I started to use react-loadable, because it says that it is possible to use with server with help of import-inspector babel plugin.
But unfortunately I got error in my server console require.ensure is not a function, which caused rerendering on my client side and I am losing all benefits of server-side rendering.
Before I had been using react-router-v3 and used getComponent with import without any problem.
Here is my routes config.
export default [
{
component: Root,
routes: [
{
path: '/',
component: Loadable({
loader: () => import('./Parent.jsx'),
loading: () => <div>Loading...</div>
}),
routes: [
{
path: '/',
exact: true,
component: Loadable({
loader: () => import('./Child.jsx'),
loading: () => <div>Loading...</div>
})
}
]
}
]
}
];
This is my .babelrc
{
presets : [["es2015", {modules: false}], "react", "stage-2", "stage-3"],
plugins: [
"transform-runtime",
"syntax-async-functions",
"dynamic-import-webpack"
],
env: {
node: {
plugins: [
["import-inspector", {
"serverSideRequirePath": true,
"webpackRequireWeakId": true,
}],
["babel-plugin-webpack-alias", {
"config": "webpack/server.js",
"findConfig": true
}]
]
}
}
}
On client it works perfectly, only error is markup checksum diffing error.
How is this supposed to work?
Thanks in advance!
Try add this to babel or babel loader
"dynamic-import-node",
That is from airbnb

Categories