In your case, xterm tries to access the window object which is not present on the server. To fix it, you have to dynamically import xterm so it only gets loaded on the client-side. i`m getting the 400 response error in react.js i know the backendd is ok but the client side i am not sure i am not fimiliar with react Getting an error "A non-serializable value was detected in the state" when using redux toolkit - but NOT with normal redux Move the import to your component's useEffect, then dynamically import the library and add your logic there.
class A:
def __init__(self, a):
self.a = a
def p(self, b = self.a): #Wrong way
print b
def p(self, b = None): #Correct way
if b is None:
b = self.a
print b
Move the import
to your component's useEffect
, then dynamically import the library and add your logic there.
useEffect(() => {
const initTerminal = async () => {
const {
Terminal
} = await import('xterm')
const term = new Terminal()
// Add logic with `term`
}
initTerminal()
}, [])
Create a component where you add the xterm
logic.
// components/terminal-component
import { Terminal } from 'xterm'
function TerminalComponent() {
const term = new Terminal()
// Add logic around `term`
return <></>
}
export default TerminalComponent
As an alternative, you could add the logic directly when dynamically importing the library with next/dynamic
to avoid having an extra file for it.
import dynamic from 'next/dynamic'
const Terminal = dynamic(
{
loader: () => import('xterm').then((mod) => mod.Terminal),
render: (props, Terminal) => {
const term = new Terminal()
// Add logic with `term`
return <></>
}
},
{
ssr: false
}
)
The library has side effects, meaning it is executing and trying to access browser specific APIs. The use case for reopening this is for an isomorphic website, we don't call or initialize the mapbox API, but it is still imported in the file, and this library does browser specific calls just from being imported, which it should not. Note that this issue tracker is for reporting bugs and feature requests. If you need general help with the node/webpack/browserify ecosystem, please refer to the documentation for those projects. Thank you!
new webpack.DefinePlugin({
__CLIENT__: !isServer // Your logic to define if webpack is running in server or client mode
}),
const mapboxGl = __CLIENT__ ?
require('mapbox-gl') :
{};
mapboxGl.accessToken = MAPBOX_TOKEN;
const map = new mapboxGl.Map({
container: this.mapContainer, // The reference to your DOM el.
style: 'mapbox://styles/mapbox/streets-v9',
center: [lng, lat],
zoom: 5,
});
import mapbox from "mapbox-gl";
import {
__ssr_safe_mapboxgl as mapboxgl
} from "./ssr-safe-mapboxgl";
const foo = new mapboxgl.Map(...)
exports.onCreateWebpackConfig = ({
stage,
loaders,
actions
}) => {
if (stage === 'build-html') {
actions.setWebpackConfig({
module: {
rules: [{
test: /mapbox-gl/,
use: loaders.null(),
}, ],
},
})
}
}
Middleware does not work at all and I get the same self is not defined error when I try to build. PS: I'm using a custom pageExtensions. Ok I have two middlewares one inside the lib folder that wraps my API and another one inside pages Thanks @marcusnunes. Actually it's clearly stated in the migration guide and in the error message, I simply didn't read carefully enough 🙈
Operating System: Platform: linux Arch: x64 Version: #58~20.04.1-Ubuntu SMP Tue Jun 14 11:29:12 UTC 2022 Binaries: Node: 16.15.1 npm: 8.1.2 Yarn: 1.22.17 pnpm: N/A Relevant packages: next: 12.2.0 eslint-config-next: N/A react: 18.2.0 react-dom: 18.2.0
import { JwtPayload, verify } from 'jsonwebtoken'
import { NextApiRequest, NextApiResponse } from 'next'
const jwtSecret = JSON.parse(process.env.AUTH_PRIVATE_KEY || ``)
export enum HASURA_ROLE {
//ROLES
}
const getToken = (authHeader: string | undefined) => {
if (typeof authHeader === 'undefined' || !authHeader) {
return false
}
const token = authHeader.split(' ')[1]
if (token) {
return verify(token, jwtSecret.key, {
algorithms: jwtSecret.type,
})
}
return false
}
export default function withAuth(middleware: any, role: HASURA_ROLE) {
// eslint-disable-next-line sonarjs/cognitive-complexity
return (request: NextApiRequest, response: NextApiResponse): Promise<any> =>
new Promise((resolve, reject) => {
let isReject = false
switch (role) {
//
}
return isReject
? reject('You are not allowed to call endpoint')
: middleware(request, response, (result: any) => async () => {
return resolve(result)
})
})
}
// middleware.ts
import type {
NextRequest
} from 'next/server'
import {
NextResponse
} from 'next/server'
// https://nextjs.org/docs/messages/middleware-upgrade-guide
const PUBLIC_FILE = /\.(.*)$/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function middleware(request: NextRequest) {
const shouldHandleLocale = !PUBLIC_FILE.test(request.nextUrl.pathname) &&
!request.nextUrl.pathname.includes('/api/') &&
request.nextUrl.locale === 'default'
return shouldHandleLocale ?
NextResponse.redirect(`/en${request.nextUrl.href}`) :
undefined
}
export {
default
}
from 'next-auth/middleware';
// /pages/middleware.page.ts
import {
NextResponse
} from 'next/server';
import type {
NextRequest
} from 'next/server';
export function middleware(req: NextRequest) {
const {
pathname
} = req.nextUrl;
if (pathname.startsWith('/about')) {
return NextResponse.redirect(new URL('/marcus', req.nextUrl));
}
}
This directory allows you to register Vue plugins before the application is created. This allows the plugin to be shared throughout your app on the Vue instance and be accessible in any component. We want the server to do as much as possible first, but sometimes it doesn’t have access to the information it needs, which results in the work being done client-side instead. Or worse, when the final content presented by the client is different from what the server expected, the client is told to rebuild it from scratch. This is a big indication that something is wrong with the application logic. Thankfully, an error will be generated in your browser’s console (in development mode) if this starts to happen. Nuxt is a framework for creating universal Vue applications. This means that it provides a structure for your project, it handles the more complicated server configuration for you, and it allows the same codebase to be deployed in various environments.
To start off, let’s use a Vue project generator called vue-cli
to quickly create a sample project:
# install vue - cli globally
npm install - g vue - cli
# create a project using a nuxt template
vue init nuxt - community / starter - template my - nuxt - project
After going through a couple options, this will create a project inside the folder my-nuxt-project
or whatever you specified. Then we just need to install dependencies and run the server:
cd my - nuxt - project npm install # Or yarn npm run dev
This is the only required directory. Any Vue components in this directory are automatically added to vue-router
based on their filenames and the directory structure. This is extremely convenient. Normally I would have a separate Pages directory anyway and have to manually register each of those components in another router file. This router file can become complex for larger projects and may need splitting to maintain readability. Instead, Nuxt will handle all of this logic for you.
To demonstrate, we can create a Vue component called about.vue
inside the Pages directory. Let’s just add a simple template such as:
<template>
<h1>About Page</h1>
</template>
You may be asking why we didn’t just create a products.vue
component in the pages directory instead like we did for the /about
page. You may think the result would be the same, but there is a difference between the two structures. Let’s demonstrate this by adding another new page.
Say we wanted a seperate About page for each employee. For example, let’s create an About page for me. It should be located at /about/ben-jones
. Initially, we may try structuring the Pages directory like this:
/pages -- | about.vue -- | /about -- -- | ben - jones.vue
When we try to access /about/ben-jones
, we instead get the about.vue
component, the same as /about
. What’s going on here?
Interestingly, what Nuxt is doing here is generating a nested route. This structure suggests that you want a permanent /about
route and anything inside that route should be nested in its own view area. In vue-router, this would be signified by specifying a <router-view />
component inside the about.vue
component. In Nuxt, this is the same concept except, instead of <router-view />
, we simply use <nuxt />
. So let’s update our about.vue
component to allow for nested routes:
<template>
<div>
<h1>About Page</h1>
<nuxt />
</div>
</template>
I wanted to redirect to other page using window.location.replace....but several times it threw the error that window is not defined....Basically in HOC there was a class component and inside the render block before the returnning the Original component I wanted to check if a variable is true or not....Hence I made a condition which will redirect to other page if variable is false.... A different solution is to load your Scroll component using dynamic imports and the srr: false option. This way your component won't even be rendered on the server-side at all. This is just an example, it can be extended adding an "element" parameter and some logic for it in the hook so you can get the scroll position of any element and get back the value to do something with it in the callback.
// components/Scroll.js
window.addEventListener("scroll", function() {
console.log("scroll!")
});
if (window !== undefined) {
// browser code
}
if (typeof window !== "undefined") {
// browser code
}
// pages/index.js
import Scroll from "../components/Scroll";
export default function Home() {
return (
<div style={{ minHeight: "1000px" }}>
<h1>Home</h1>
<Scroll />
</div>
);
}
// components/Scroll.js
import React, {
useEffect
} from "react";
export default function Scroll() {
useEffect(function onFirstMount() {
function onScroll() {
console.log("scroll!");
}
window.addEventListener("scroll", onScroll);
}, []); // empty dependencies array means "run this once on first mount"
return null;
}
However, one case where one needs to explicitly access the global object is when writing to it, usually for the purpose of polyfills. Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non–strict mode, but this will be undefined in modules and inside functions running in strict mode. You can also use Function('return this')(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way. With globalThis available, the additional search for the global across environments is not necessary anymore:
console.log(window.Math === Math); // true
function check(it) {
// Math is known to exist as a global in every environment.
return it && it.Math === Math && it;
}
const globalObject =
check(typeof window === 'object' && window) ||
check(typeof self === 'object' && self) ||
check(typeof global === 'object' && global) ||
// This returns undefined when running in strict mode
(function() {
return this;
})() ||
Function('return this')();
if (typeof globalObject.Intl === 'undefined') {
// No Intl in this environment; define our own on the global scope
Object.defineProperty(globalObject, 'Intl', {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
Do not copy/paste these <script src=... URLs from this page; they refer to a specific version of the SDK. To get the <script src=...></script> markup for the latest version, always go to https://www.npmjs.com/package/@microsoft/teams-js. You can also reference the entire library in html pages using a script tag. There are three ways to do this: If you are a TypeScript developer it is helpful to install the NPM package as described above, even if you don't link to the copy of MicrosoftTeams.min.js in node_modules from your HTML, because IDEs such as Visual Studio Code will use it for Intellisense and type checking.
If you are using any dependency loader or module bundler such as RequireJS, SystemJS, browserify, or webpack, you can use import
syntax to import specific modules. For example:
import * as microsoftTeams from "@microsoft/teams-js";
<!-- Microsoft Teams JavaScript API (via CDN) -->
<script src="https://res.cdn.office.net/teams-js/2.0.0/js/MicrosoftTeams.min.js" integrity="sha384-QtTBFeFlfRDZBfwHJHYQp7MdLJ2C3sfAEB1Qpy+YblvjavBye+q87TELpTnvlXw4" crossorigin="anonymous"></script>
<!-- Microsoft Teams JavaScript API (via npm) -->
<script src="node_modules/@microsoft/teams-js@2.0.0/dist/MicrosoftTeams.min.js"></script>
<!-- Microsoft Teams JavaScript API (via local) -->
<script src="MicrosoftTeams.min.js"></script>