Missing meta information in "view-page-source" - next.js

I need basic webpage description for SEO in Next.js project, but it is missing in the page source. However it is shown in chrome developer tools on Elements tab. What I am doing wrong?
my _app.js file-
import { useState, useEffect } from 'react';
import Head from 'next/head';
import Layout from '../components/layout/Layout';
import ContextProvider from '../store/context';
import '../styles/globals.css';
import '../styles/sideDrawer.css';
function MyApp({ Component, pageProps }) {
const [showChild, setShowChild] = useState(false);
useEffect(() => {
setShowChild(true);
}, []);
if (!showChild) {
return null;
}
if (typeof window === 'undefined') {
return <></>;
} else {
return (
<>
<Head>
<title>Reklaminiai.lt</title>
<meta name="description" content="reklaminės prekės ir aksesuarai" />
</Head>
<ContextProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</ContextProvider>
</>
);
}
}
export default MyApp;
view-source:
<!DOCTYPE html><html><head><style data-next-hide-fouc="true">body{display:none}</style><noscript data-next-hide-fouc="true"><style>body{display:block}</style></noscript><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><meta name="next-head-count" content="2"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills.js?ts=1675875034598"></script><script src="/_next/static/chunks/webpack.js?ts=1675875034598" defer=""></script><script src="/_next/static/chunks/main.js?ts=1675875034598" defer=""></script><script src="/_next/static/chunks/pages/_app.js?ts=1675875034598" defer=""></script><script src="/_next/static/chunks/pages/index.js?ts=1675875034598" defer=""></script><script src="/_next/static/development/_buildManifest.js?ts=1675875034598" defer=""></script><script src="/_next/static/development/_ssgManifest.js?ts=1675875034598" defer=""></script><noscript id="__next_css__DO_NOT_USE__"></noscript></head><body><div id="__next"></div><script src="/_next/static/chunks/react-refresh.js?ts=1675875034598"></script><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{}},"page":"/","query":{},"buildId":"development","nextExport":true,"autoExport":true,"isFallback":false,"scriptLoader":[]}</script></body></html>
I found information on this topic, but nothing solved my problem.

Related

NextJS dynamic metatag without getServerSideProps

i want when u share a link from a topic in my forum it shows the title as the topic title, just like https://facebook.com/
that shows Facebook - log in or sign up
but i cant use
getServerSideProps
because i'm using html files to host (i need to) next build && next export -o
and its not supported on static html export:
https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features
there is any other way to make it work?
i tried:
import React from "react";
import { useQuery } from "react-query";
import { fetchTopic } from "../../fetchers/forum";
import EmptyChangingPage from "../empty";
import Head from "next/head";
import { useRouter } from "next/router";
import { baseURL } from "../../baseUrl";
export default function Topic() {
const router = useRouter();
const { topicId } = router.query;
//
const {
data: topic,
isLoading: isLoadingTopic,
isFetched: isFetchedTopic,
} = useQuery([`topic:${topicId}`], () => fetchTopic(Number(topicId)), {
staleTime: 60000,
enabled: topicId !== undefined,
});
if (isLoadingTopic || !isFetchedTopic)
return <EmptyChangingPage />;
return (
<>
<Head>
<meta property="og:type" content="website" />
<meta
property="og:image"
content={`http://${baseURL}/imgs/og_logo.png`}
/>
<meta
property="og:url"
content={`http:/${baseURL}/forum/topic/?topicId=${topic?.topicId}`}
/>
<meta property="og:title" content={`Forum - ${topic?.title}`} />
<meta
property="og:description"
content={`content - ${topic?.message}`}
/>
</Head>
<main>
<div style={{ backgroundColor: "#dcdcdc" }}>
{/* forum stuff */}
</div>
</main>
</>
);
}
but when i send a link it shows
Forum - undefined
content - undefined

How to use TailwindCSS with Material UI?

I am using Next.js with Material UI. I am having troubles with using Tailwind with MUI. I've been following this guide but it still doesn't work. The file loads but the classes just don't apply. If someone could help, that would be wonderful!
My Tailwind Config
module.exports = {
important: "#__next",
content: ["./pages/**/*.{js,jsx}"],
theme: {
extend: {},
},
plugins: [],
}
My _app.js
//import '../styles/globals.css'
//function MyApp({ Component, pageProps }) {
// return <Component {...pageProps} />
//}
//export default MyApp
import '../styles/edit.css';
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider, StyledEngineProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline';
import { CacheProvider } from '#emotion/react';
import theme from '../config/themeConfig';
import createEmotionCache from '../functions/createEmotionCache';
import Layout from "../components/Layout";
//import '../styles/tailwind.css';
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
export default function MyApp(props) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
return (
<Layout>
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<StyledEngineProvider injectFirst>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</StyledEngineProvider>
</ThemeProvider>
</CacheProvider>
</Layout>
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
emotionCache: PropTypes.object,
pageProps: PropTypes.object.isRequired,
};
Thanks!
You didn't follow the guide ( https://mui.com/material-ui/guides/interoperability/#tailwind-css ) correctly.
In your tailwind.config.js file you need to set the corePlugins parameter to disable the preflight CSS. The preflight CSS is overriding some of the styles of MUI.

getServerSideProps not working returning undefined when mapping next js

what am i doing wrong here? i am trying to do getServerSideProps but
localhost is working fine when hosted i get
Internal Server Error 500
index.js
import React from "react";
import Head from "next/head";
import Navigation from "./navigation";
import { GetServerSideProps } from "next";
// import MyEditor from "./editor";
import Form from "react-bootstrap/Form";
import { useState } from "react";
import Questions3 from "../pages/question";
import axios from "axios";
import { FormControl, Button } from "react-bootstrap";
import InputGroup from "react-bootstrap/InputGroup";
function Home({ data }) {
const [Questions, setQuestions] = useState();
const [deatils1, setdeatils] = useState();
function clickQuestion() {
axios
.post("https://ask-over.herokuapp.com/questionpost", {
Name: Questions,
Summary: deatils1,
// username: this.props.sign.displayName,
// useremail: this.props.sign.email,
})
.then(() => {
window.location.reload();
});
}
function question(e) {
setQuestions(e.target.value);
// this.setState({ ask: e.target.value });
}
function deatils(e) {
setdeatils(e.target.value);
// this.setState({ ask: e.target.value });
}
return (
<>
<Head>
<title>wixten </title>
<meta
name="google-site-verification"
content="rqVH7Jc-L-NyyCYGf2LOEjRPFEUvi8iImncslSfxtac"
/>
<link rel="shortcut icon" href="/wixten.png" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta
name="description"
content="have all ur doubts cleared here at wixten . At wixten ask any thing you want and anyone in the world can see your questin and will be able to answer it "
/>
</Head>
<Navigation />
<div>
<div className="container search-box">
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Title</Form.Label>
<Form.Control
type="text"
onChange={question}
placeholder="ask anything?"
/>
</Form.Group>
<Form.Group
className="mb-3"
controlId="exampleForm.ControlTextarea1"
>
<Form.Label>question</Form.Label>
<Form.Control onChange={deatils} as="textarea" rows={3} />
</Form.Group>
</Form>
{/* <Form>
<InputGroup
className="mb-3"
// onChange={this.question}
// value={ask}
// value={this.state.ask}
>
<FormControl
placeholder="ask anything?"
aria-label="ask anything?"
// aria-label="ask anything?"
aria-describedby="basic-addon2"
/>
<FormControl as="textarea" rows={3} />
</InputGroup>
</Form> */}
<Button
type="submit"
disabled={!deatils1 || !Questions}
onClick={clickQuestion}
variant="outline-secondary"
id="button-addon2"
>
ask?
</Button>
<Questions3 data={data} />
</div>
</div>
</>
);
}
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://ask-over.herokuapp.com/questapi`);
const data = await res.json();
// console.log(data);
// Pass data to the page via props
return { props: { data } };
}
export default Home;
pages/question/index.jsx
import React from "react";
import Alert from "react-bootstrap/Alert";
import axios from "axios";
import { useState } from "react";
import { useEffect } from "react";
import Link from "next/link";
import Head from "next/head";
function Question3(props) {
const data = props.data;
return (
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "query/[itm]",
}}
as={`query/${encodeURIComponent(itm._id)}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
);
}
export default Question3;
when i call http://localhost:3000/the question page is rendering
after deploying to vercel i get the following error
when i depolyed i get this error
This looks like it's a non-page component. You can't use getServerSideProps in non-page components.
Try calling the API from your page file and pass it down as props. You could also create a context.
getServerSideProps can only be exported from a page. You can’t export it from non-page files.
Source

Ordering problem using css import alongside styled components in nextjs app

I am using NextJS and when I use direct css import ...css alongside a styled-component createGlobalStyle. My direct css imports are always included last in my html causing some overriding issues that I've setup in GlobalStyles.
How can I resolve this?
rendered html
<head>
<link href="/_next/static/chunks/main.js?ts=1609163560022">
<style></style> // global styled component
<style></style> // bootstrap imported after global styled component
</head>
_app.js
import { ThemeProvider } from "styled-components";
import 'bootstrap/dist/css/bootstrap.min.css' // this is always loaded last <head>
import GlobalStylesfrom 'styles/global'; // this is always loaded first in <head>
const theme = {
...
};
export default function App({ Component, pageProps }) {
return (
<ThemeProvider theme={theme}>
<GlobalStyles/>
<Component {...pageProps} />
</ThemeProvider>
)
}
_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet();
const page = renderPage(App => props =>
sheet.collectStyles(<App {...props} />)
);
const styleTags = sheet.getStyleElement();
return { ...page, styleTags };
}
render() {
return (
<Html>
<Head>{this.props.styleTags}</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

How to make my scripts work on my components in next.js?

I have a problem with my script, I am using next and React in my pages / _app.js file I have the following code:
import axios from "axios";
import { $ } from "jquery";
import App from "next/app";
import Router from "next/router";
import { destroyCookie, parseCookies } from "nookies";
import Layout from "../components/_App/Layout";
import "../public/css/boot.css";
import "../public/css/icons.css";
import "../public/css/themes/style.css";
import "../public/jquery";
import "../public/scripts";
import baseUrl from "../utils/baseUrl";
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const { token } = parseCookies(ctx);
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
if (!token) {
const isProtectedRoute =
ctx.pathname === "/profile" ||
ctx.pathname === "/admin/add-product" ||
ctx.pathname === "/my-orders-history" ||
ctx.pathname === "/admin/users" ||
ctx.pathname === "/admin/dashboard";
if (isProtectedRoute) {
redirectUser(ctx, "/auth/login");
}
} else {
try {
const payload = { headers: { Authorization: token } };
const url = `${baseUrl}/api/account`;
const response = await axios.get(url, payload);
const user = response.data;
const isRoot = user.role == "root";
const isAdmin = user.role == "admin";
// if authenticated but not root or admin
const isNotPermitted =
!(isRoot || isAdmin) &&
(ctx.pathname === "/admin/add-product" ||
ctx.pathname === "/admin/customers" ||
ctx.pathname === "/admin/orders" ||
ctx.pathname === "/admin/dashboard");
if (isNotPermitted) {
redirectUser(ctx, "/products");
}
pageProps.user = user;
} catch (error) {
// console.error("Error getting current user", error);
//invalid token
destroyCookie(ctx, "token");
redirectUser(ctx, "/auth/login");
}
}
return { pageProps };
}
componentDidMount() {
window.addEventListener("storage", this.syncLogout);
require($)(window);
}
syncLogout = e => {
if (e.key === "logout") {
Router.push("/");
}
};
render() {
const { Component, pageProps } = this.props;
return (
<Layout {...pageProps}>
<Component {...pageProps} />
</Layout>
);
}
}
export default MyApp;
In my components/_App/Layouts.js tenho o seguinte codigo:
import React from "react";
import Head from "next/head";
import Footer from "./Footer";
import StaticHeader from "./StaticHeader";
const Layout = ({ children, user }) => {
return (
<React.Fragment>
<Head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WdpShoes | Home</title>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Open+Sans:wght#400;700;800&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="./public/css/icons.css" />
<link href="https://file.myfontastic.com/gMNiHf8HU5GG4r6y622k2N/icons.css" rel="stylesheet" />
<link rel="stylesheet" href="/css/boot.css" />
<link rel="stylesheet" href="/css/themes/style.css" />
<link rel="shortcut icon" href="/css/themes/logo/favicon.png" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</Head>
<body>
<StaticHeader user={user} />
{children}
<Footer />
<script src="/jquery.js"></script>
<script src="/scripts.js"></script>
<script src="/css/themes/script.js"></script>
</body>
</React.Fragment>
);
};
export default Layout;
In the Components that are in my Layout the jquery and javascript are working but in my components they are not
When I import my script into my pages / _app.js file I encounter the following error:
ReferenceError: $ is not defined
at Object../public/scripts.js (C:\Users\walter\Desktop\mystore.next\server\pages_app.js:5217:1)
I looked for some materials and I didn't find anything that could help me solve this problem that is preventing me from developing several projects
I know the purpose of the site is to answer questions but to better explain my problem I have the complete code at:
https://codesandbox.io/s/dawn-mountain-vme5e?file=/pages/_app.js
And in its current state it encounters the Internal Server Error due to the fact that the $ function is returning an undefined,Because my script and jquery are not working correctly in my components
To understand your issue, a little theory is needed. Next.js uses server-side rendering and static generation, which means the all code is initially run on the server. jQuery is a client-side library and it can't run on the server. Therefore, you need to ensure that all the jQuery code is executed only on the client side. You can do this by checking if the window object exists and only then executing jQuery. Also, you've forgotten to include jQuery in your scripts.js file.
Modify the
scripts.js file:
import $ from "jquery";
if (typeof window !== "undefined") {
$(function () {
// Rest of the code...
}
}
Next, modify the componentDidMount function in _app.js:
componentDidMount() {
window.addEventListener("storage", this.syncLogout);
}

Resources