Skip to content

Instantly share code, notes, and snippets.

@anthonynsimon
Last active October 31, 2020 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonynsimon/30a64a7af7c2d4430d32ab5f84cd1f79 to your computer and use it in GitHub Desktop.
Save anthonynsimon/30a64a7af7c2d4430d32ab5f84cd1f79 to your computer and use it in GitHub Desktop.
Panelbear NextJS integration
// MIT License
// Copyright (c) 2020 Anthony N. Simon
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Document, { Head, Html, Main, NextScript } from "next/document";
// IMPORTANT: remember to set site ID below.
// You can enable debug mode when developing to allow Panelbear to send events on localhost.
const PANELBEAR_CONFIG = {
site: "YOUR_SITE_ID",
spaMode: "history",
debug: false,
};
function getPanelbearScript() {
if (PANELBEAR_CONFIG.debug) {
console.warn(
"Panelbear is running in debug mode, you should probably turn this off for production."
);
}
if (!PANELBEAR_CONFIG.site || PANELBEAR_CONFIG.site === "YOUR_SITE_ID") {
console.warn("You should set your Panelbear site ID.");
}
return `window.panelbear = window.panelbear || function(){ window.panelbearQ = window.panelbearQ || []; panelbearQ.push(arguments); };
panelbear("config", ${JSON.stringify(PANELBEAR_CONFIG)});
`;
}
class CustomDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head>
<script
async
src={`https://cdn.panelbear.com/analytics.js?site=${PANELBEAR_CONFIG.site}`}
></script>
<script
dangerouslySetInnerHTML={{ __html: getPanelbearScript() }}
></script>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default CustomDocument;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment